问题描述:
开发过程中往往查询出来的内容是多列,但是因为框架中的grid的原因需要将这多行设置为一行中的多列,思路是通过case when转换将多行转换为一行中的多列。
表结构和表结构如下:
统计各个类型的数量,将其放入echarts或grid中,一般的根据类型统计的SQL如下:
select t.type,sum(1) num from test t group by t.type order by t.type
查询结果如下:
可见途中是一类一行如果将一行转化为一行中的一列:
需求效果图如下:
通过case when 实现转换,SQL如下:
select sum(case
when type = 'A' then
num
else
0
end) A,
sum(case
when type = 'B' then
num
else
0
end) B,
sum(case
when type = 'C' then
num
else
0
end) C,
sum(case
when type = 'D' then
num
else
0
end) D
from (select t.type, sum(1) num
from test t
group by t.type
order by t.type)