php+mysql 输出table 如何横向排列

数据库表 table

idcidriqirate
11220181200
21220191300
31220201400
41320182200
51320192600
61320201900

正常SELECT出来,然后php 遍历输出是竖排,如何才能向下面这样横排呢?

cid202020192018
12140013001200
13190026002200

最简单的方式的确是像楼上说的那样用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