[英]SQL How to transform ROWS to COLUMNS and COLUMNS TO ROWS? db2
I have an SQL query which works fine in DB2 My result is 我有一个在DB2中正常工作的SQL查询,我的结果是
SERVICE IN OUT INPROGRESS
ADSL 1 5 10
VOIP 15 12 11
IPTV 20 14 17
Now I want to transform it to be like this: 现在,我想将其转换为如下形式:
CLASS ADSL VOIP IPTV
IN 1 5 10
OUT 15 12 11
INPROGRESS 20 14 17
Although it seems long my SQL is very simple but I never had transformed this. 虽然看起来我的SQL很长很简单,但是我从未改变过它。 If someone knows I will be thankful.
如果有人知道我会很感激的。
My SQL is 我的SQL是
select distinct 'ADSL' as SERVICE,
(select count(*) as In from ticket
where
(class='C1' and
(servicesinfault='25'))),
(select count(*) as Out from ticket
where
(class='C2' and
(servicesinfault='25'))),
(select count(*) as In_progress from ticket
where
(class='C3' and
(servicesinfault='25')))
from ticket where servicesinfault = '25'
union all
select distinct 'VoIP',
(select count(*) from ticket
where
(class='C1' and
(servicesinfault='26'))),
(select count(*) from ticket
where
(class='C2' and
(servicesinfault='26'))),
(select count(*) from ticket
where
(class='C3' and
(servicesinfault='26')))
from ticket where servicesinfault = '26'
union all
select distinct 'IPTV',
(select count(*) from ticket
where
(class='C1' and
(ticket.servicesinfault='27'))),
(select count(*) from ticket
where
(class='C2' and
(servicesinfault='27'))),
(select count(*) from ticket
where
(class='C3' and
(servicesinfault='27')))
from ticket where servicesinfault = '27'
Just as a remark, your result should like: 谨此声明,您的结果应为:
CLASS ADSL VOIP IPTV
IN 1 15 20
OUT 5 12 14
INPROGRESS 10 11 17
The pivoted version should be something like: 透视版本应为:
select distinct 'In' as CLASS,
(select count(*) as 'ADSL'
from ticket
where (class = 'C1' and (servicesinfault = '25'))),
(select count(*) as 'VoIP'
from ticket
where (class = 'C1' and (servicesinfault = '26'))),
(select count(*) as 'IPTV'
from ticket
where (class = 'C1' and (servicesinfault = '27')))
from ticket
where class = 'C1'
union all
select distinct 'Out',
(select count(*)
from ticket
where (class = 'C2' and (servicesinfault = '25'))),
(select count(*)
from ticket
where (class = 'C2' and (servicesinfault = '26'))),
(select count(*)
from ticket
where (class = 'C2' and (servicesinfault = '27')))
from ticket
where class = 'C2'
union all
select distinct 'InProgress',
(select count(*)
from ticket
where (class = 'C3' and (ticket.servicesinfault = '25'))),
(select count(*)
from ticket
where (class = 'C3' and (servicesinfault = '26'))),
(select count(*)
from ticket
where (class = 'C3' and (servicesinfault = '27')))
from ticket
where class = 'C3'
The word you are looking for is "PIVOT". 您要查找的单词是“ PIVOT”。
If your DBMS doesn't offer one, you can use the "poor man's pivot". 如果您的DBMS不提供,则可以使用“穷人的支点”。
Look at usr's answer on this question: 查看usr关于此问题的答案:
Poor Man's SQL Pivot. 可怜的人的SQL枢轴。 List Questions as Columns and Answers per User in one row
在每一行中将问题列为每位用户的列和答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.