枢轴 table 加入其他 table

Pivot table with join other table

我想询问关于枢轴 table 和其他 table 的问题。它看起来像下面这样:

结果

|   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 |

那个table来自下面这两个table:

Table硕士

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

Table类型

|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  |

我试过下面这段代码,但没有成功。

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

错误如下所示:

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

我还有其他相关问题。如何在视图 codeigniter 中显示结果 table。假设我有一个控制器来 select 所有数据,如下面的代码:

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');
}
}

我不知道模型是如何工作的,它是否编写了与我获得结果时相同的查询。或者也许还有其他方法。 我猜也认为它很复杂。这是我做的视图。

<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>

非常感谢您的帮助。

您可以使用动态交叉表:

SQL Fiddle

SET @sql = NULL;

SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN m.idType = ',
      Id,
      ' THEN value END) AS ',
      Type
    )
  ) INTO @sql
FROM tblType;

SET @sql =
  CONCAT('SELECT m.Date, ', @sql, ' FROM tblMaster m INNER JOIN tblType t ON t.Id = m.idType GROUP BY m.Date ORDER BY m.Date');


PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

阅读此 article 了解有关动态枢轴的更多信息。