我有以下查询,它基本上显示了在几周内按用户发送的邮件数量。
有许多不同的消息类型,我希望每周在一行中将这些结果视为单独的列,但似乎无法找到实现这些结果的最佳方式..
所以我想最终得到类似的东西。
Col1,Col2,Col3,Col4,Col5,Col6
Username,Week,TotalofMessage,TypeA,TypeB,TypeC
目前我为每个用户名,周,类型获取一个单独的行。因此,对于3种不同的类型,我有三个ROWS。
SELECT
ui.display_name, to_char(msg.received_at,'yyyy IW'),
msg.message_type_id, count(msg.message_id) AS MESSAGES
FROM
message msg
INNER JOIN
user_info ui ON ui.entity_id = msg.from_entity
WHERE
msg.received_at > sysdate -30
AND msg.from_entity = 2
GROUP BY
ui.display_name, to_char(msg.received_at,'yyyy IW'), msg.message_type_id
ORDER BY
to_char(msg.received_at,'yyyy IW') DESC
任何指针都会有所帮助。
感谢。
答案 0 :(得分:0)
您可以对要执行的操作使用条件聚合:
SELECT ui.display_name, to_char(msg.received_at, 'yyyy IW'),
count(msg.message_id) AS MESSAGES,
sum(case when msg.message_type_id = A then 1 else 0 end) as messages_a,
sum(case when msg.message_type_id = B then 1 else 0 end) as messages_b,
sum(case when msg.message_type_id = C then 1 else 0 end) as messages_c
FROM message msg INNER JOIN
user_info ui
ON ui.entity_id = msg.from_entity
WHERE msg.received_at > sysdate -30 AND msg.from_entity = 2
GROUP BY ui.display_name, to_char(msg.received_at,'yyyy IW')
ORDER BY to_char(msg.received_at,'yyyy IW') DESC;
使用适当的值填写A
,B
和C
。请注意,我还从message_type_id
删除了group by
。