Oracle - 透视聚合函数结果

标签 oracle aggregate-functions pivot-table

我有一个保存用户日常事件的表格,现在我必须以以下形式在报告中呈现这些事件。

enter image description here

我写了一个查询,

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/

相关文章:

sql - 选择语句抛出 "ORA-00907: missing right parenthesis"

performance - 识别架构列表中具有过时统计信息的分区

sql - Oracle 12c 以一种奇怪的方式解释 SQL(内部查询)

oracle - 在 PL/SQL block 内的 SQL 中使用嵌套表变量/集合

mysql - SQL 根据匹配值将多行合并为单行

sql - postgres中数组聚合的算术运算

mysql - GROUP_CONCAT() 不能单独使用?

php - Laravel 5.1 - 3 个表之间的数据透视表

mysql - 如何在 MySQL 中将行拆分为多列

vba - 数据透视表位于同一工作表上