Pivot table with join other table

I wanna ask about pivot table with join other table. Its look like this below:

Result

|   DATE    | A | B  | C  | D  |
|-----------|---|----|----|----|
|2015-06-01 |10 | 20 | 30 | 20 |
|2015-06-02 |20 | 30 | 40 | 20 |
|2015-06-03 |40 | 10 | 10 | 20 |

That table came from this two table below:

Table Master

|ID|Type|
|--|----|
|1 |A   |
|2 |B   |
|3 |C   |

Table Type

|ID|Date      | idType |value|
|--|----------|--------|-----|
|1 |2015-06-01| 1      | 10  |
|2 |2015-06-01| 2      | 20  |
|3 |2015-06-01| 3      | 30  |
|4 |2015-06-01| 4      | 20  |
|5 |2015-06-02| 1      | 20  |
|6 |2015-06-02| 2      | 30  |
|7 |2015-06-02| 3      | 40  |
|8 |2015-06-02| 4      | 20  |
|9 |2015-06-03| 1      | 40  |
|10|2015-06-03| 2      | 10  |
|11|2015-06-03| 3      | 10  |
|12|2015-06-03| 4      | 20  |

I tried this code below, but its not succsess.

SELECT * FROM ( SELECT tgl_nab, idtype, nilai FROM jts_test ) src pivot (sum(nilai) for idtype in ([1], [2], [3],[4]) ) piv;

The error show like this below:

You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ‘pivot (sum(nilai) for idtype in ([1], [2], [3],[4]) ) piv LIMIT
0, 25’ at line 1

And i have other related question too. How do show the result table in view codeigniter. Let say i have a controller to select all data, like this code below:

public function test()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['test'] = $this->report_m->get_allcontentest();
$this->load->view('header');
$this->load->view('report/test_list_view',$data);
$this->load->view('footer');
} else {
    redirect('login');
}
}

and i dont how the model work, is it write the same query as when i get the result. or maybe there is other way.
also in the view its complicated i guess. here’s the view i made.

<div class="box-body table-responsive">
          <table id="datatable" class="table table-bordered table-hover">
            <thead>
              <tr>
                <th>No</th>
                <th><?php echo $baris->type; ?></th>
                <th>Created At</th>
                <th>Menu</th>
              </tr>
            </thead>
            <tbody>
              <?php
                foreach($report as $baris){
              ?>
              <tr>
                <td><?php echo $baris->id; ?></td>
                <td><?php echo $baris->nilai; ?></td>
                <td><?php echo $baris->create; ?></td>
                <td>
                  <a href="#" class="fa fa-eye"></a>
                </td>
              </tr>
              <?php
                }
              ?>
            </tbody>
          </table>
        </div>

really appriciete your help.


Source: mysql

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.