我有一个大的SQL查询,它连接多个表中的列以提供这种格式的数据:
ID CODE Count Action
-----------------------------
1 A 02 VIEWED
1 A 22 CLICKED
1 A 45 PRINTED
1 A 32 SCHEDULED
2 A 34 VIEWED
2 B 14 CLICKED
2 B 23 PRINTED
2 B 78 SCHEDULED
.
.
X D 12 CLICKED
行动的价值只能是VIEWED,CLICKED,SCHEDULED,PRINTED。 ID,CODE的每个组合最多包含4行。如果没有行动计数说'点击',那么该行不存在
所以,一旦我得到了结果集,我想将它展平以获得这种格式的数据:
Id CODE VIEWED CLICKED PRINTED SCHEDULED
-----------------------------------------------
1 A 02 11 45 32
1 B 54 57 89 45
2 B 34 14 23 78
3 G null null 28 20
X D null 12 null null
我的查询做了很多事情,但简而言之:
SELECT ID,CODE, ACTION, COUNT(*) AS COUNT
FROM MY_TABLE
GROUP BY ID,CODE,ACTION.
在这一个查询中,我想获取结果集然后展平行。我不能使用union-alls等多次查询数据库。
数据库是Oracle 9i数据库,因此枢轴功能不起作用。
答案 0 :(得分:1)
应该能够SUM
与CASE
一起使用,从您的ACTION
条款中移除GROUP BY
:
SELECT ID,
CODE,
SUM(CASE WHEN ACTION = 'VIEWED' THEN 1 ELSE 0 END) Viewed,
SUM(CASE WHEN ACTION = 'CLICKED' THEN 1 ELSE 0 END) Clicked,
SUM(CASE WHEN ACTION = 'PRINTED' THEN 1 ELSE 0 END) Printed,
SUM(CASE WHEN ACTION = 'SCHEDULED' THEN 1 ELSE 0 END) Scheduled
FROM MY_TABLE
GROUP BY ID,
CODE
答案 1 :(得分:0)
select id,code,decode(action,'VIEWED',count,'null') viewed,
decode(action,'CLICKED',count,'null') Clicked,
decode(action,'PRINTED',count,'null') Printed,
decode(action,'SCHEDULED',count,'null') Scheduled from you_table groub by ID,CODE;