我有一个保存用户日常事件的表格,现在我必须以以下形式在报告中呈现这些事件。
我写了一个查询,
select ua.UserID, count(ua.UserID),
(select count(*) form user_activities t1 where t1.UserID = ua.UserID and ActivityID = 1 and t1.Date = ua.Date group by t1.UserID, t1.ActivityID, t1.Date) as Meeting,
(select count(*) form user_activities t1 where t1.UserID = ua.UserID and ActivityID = 2 and t1.Date = ua.Date group by t1.UserID, t1.ActivityID, t1.Date) as Training,
ua.Date
from user_activities ua
group by ua.UserID, ua.ActivityID, ua.Date
但我知道这不是一种有效的方法,并且事件 ID 是硬编码的,将来可能会出现新类型的事件。
你能指导我让它变得更加动态和高效吗?
谢谢
最佳答案
您可以使用PIVOT ,添加在辅助子查询中使用的总事件分析函数。
with tab2 as (
select USERID, ACTIVITYID, TRANS_DATE,
count(*) over (partition by USERID, TRANS_DATE) as total_activities
from tab)
select * from tab2
PIVOT (count(*) for (activityId) in
('Meeting' as "MEETING",
'Outdoor' as "OUTDOOR",
'Training' as "TRAINING"))
;
返回
USERID TRANS_DATE TOTAL_ACTIVITIES MEETING OUTDOOR TRAINING
---------- ----------------- ---------------- ---------- ---------- ----------
1 28.12.15 00:00:00 2 0 1 1
3 28.12.15 00:00:00 2 1 1 0
2 28.12.15 00:00:00 2 2 0 0
不幸的是,静态选择无法对新事件使用react并自动添加列。
您必须通过为新事件添加一行来更新 PIVOT for 子句中的列表。
您可以使用此支持查询来创建实际列表(删除最后一个逗号)
select distinct ''''||activityId ||''' as "'||activityId||'",' from tab order by 1;
关于Oracle - 透视聚合函数结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34498382/