我有一个SQL查询,可以在DB2中正常工作 我的结果是
SERVICE IN OUT INPROGRESS
ADSL 1 5 10
VOIP 15 12 11
IPTV 20 14 17
现在我想把它变成这样:
CLASS ADSL VOIP IPTV
IN 1 5 10
OUT 15 12 11
INPROGRESS 20 14 17
虽然看起来我的SQL很简单,但我从来没有改变过这个。如果有人知道我会感激。
我的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'
答案 0 :(得分:1)
请注意,您的结果应该是:
CLASS ADSL VOIP IPTV
IN 1 15 20
OUT 5 12 14
INPROGRESS 10 11 17
旋转版本应该是这样的:
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'
答案 1 :(得分:0)
你要找的是“PIVOT”。
如果您的DBMS没有提供,您可以使用“穷人的支点”。
看看usr对这个问题的回答:
Poor Man's SQL Pivot. List Questions as Columns and Answers per User in one row