php mysql显示行数据到列

时间:2017-02-20 14:36:06

标签: php mysql

您好我需要帮助在php mysql中显示行到列的数据 原始数据如下所示:

date                bank             total 
----------------------------------------------
2017-02-01           BCA            2500000
2017-02-01           CIMB           1500000
2017-02-01           UOB            3750000
2017-02-02           BCA            2100000
2017-02-02           CIMB           3600000
2017-02-02           UOB            2500000

以及我对输出的期望如下:

date            BCA          CIMB          UOB       TOTAL
----------------------------------------------------------------
2017-02-01    2500000       1500000      3750000    7750000
2017-02-02    2100000       3600000      2500000    8200000

所以,如果您有任何建议制作php mysql代码,请帮助我, 谢谢

1 个答案:

答案 0 :(得分:0)

将行转换为列称为pivot。 最常见的方法是使用GROUP BY和MAX或SUM等函数。

创建/插入查询

CREATE TABLE t
    (`date` DATE, `bank` VARCHAR(4), `total` INT)
;

INSERT INTO t
    (`date`, `bank`, `total`)
VALUES
    ('2017-02-01', 'BCA', 2500000),
    ('2017-02-01', 'CIMB', 1500000),
    ('2017-02-01', 'UOB', 3750000),
    ('2017-02-02', 'BCA', 2100000),
    ('2017-02-02', 'CIMB', 3600000),
    ('2017-02-02', 'UOB', 2500000)
;

<强>查询

SELECT
   t.date 
 , MAX(CASE WHEN t.bank = 'BCA' THEN t.total END) AS BCA
 , MAX(CASE WHEN t.bank = 'CIMB' THEN t.total END) AS CIMB
 , MAX(CASE WHEN t.bank = 'UOB' THEN t.total END) AS UOB
 , SUM(t.total) AS total
FROM 
 t
GROUP BY 
 t.date 
ORDER BY 
 t.date ASC 

<强>结果

date            BCA     CIMB      UOB  total    
----------  -------  -------  -------  ---------
2017-02-01  2500000  1500000  3750000  7750000  
2017-02-02  2100000  3600000  2500000  8200000