数据库表 table
id | cid | riqi | rate |
---|---|---|---|
1 | 12 | 2018 | 1200 |
2 | 12 | 2019 | 1300 |
3 | 12 | 2020 | 1400 |
4 | 13 | 2018 | 2200 |
5 | 13 | 2019 | 2600 |
6 | 13 | 2020 | 1900 |
正常SELECT出来,然后php 遍历输出是竖排,如何才能向下面这样横排呢?
cid | 2020 | 2019 | 2018 |
---|---|---|---|
12 | 1400 | 1300 | 1200 |
13 | 1900 | 2600 | 2200 |
最简单的方式的确是像楼上说的那样用case when ,比如
select cid,
max( case when riqi='2020' then rate else 0 end ),
max( case when riqi='2019' then rate else 0 end ),
max( case when riqi='2018' then rate else 0 end )
from table group by cid;
但是这有个缺陷,sql查询时必须固定好有多少列,因此这个sql是无法通过你数据的变化来动态变化列数的,只能先查一次数据,获得可能的值,再动态拼接sql来执行查询。
select cid,riqi,sum(rate) from table group by cid,riqi;
然后case when 判断一下 应该就可以了
类似于这样:
SELECT Year,
SUM(CASE Quarter WHEN 1 THEN Amount ELSE 0 END) AS Q1,
SUM(CASE Quarter WHEN 2 THEN Amount ELSE 0 END) AS Q2,
SUM(CASE Quarter WHEN 3 THEN Amount ELSE 0 END) AS Q3,
SUM(CASE Quarter WHEN 4 THEN Amount ELSE 0 END) AS Q4
FROM Northwind.dbo.Pivot
GROUP BY Year