[英]SQL Server aggregation query
I have a table called EventLog
like this:我有一个名为
EventLog
的表,如下所示:
I would like to display the count of each event type for each deviceId
like so:我想显示每个
deviceId
的每个事件类型的计数,如下所示:
Then, ultimately, show only devices where the type3 count and type4 counts differ:然后,最终只显示 type3 计数和 type4 计数不同的设备:
I know I will need to use COUNT
and GROUP BY
and possibly a nested SELECT
?我知道我需要使用
COUNT
和GROUP BY
可能还有嵌套的SELECT
?
I've tried:我试过了:
SELECT
deviceId,
MIN(eventType) AS [Type3],
MAX(eventType) AS [Type4]
FROM
EventLog
WHERE
eventType IN (3,4)
GROUP BY
deviceId;
But that just returns the minimum and maximum value for each deviceID
instead of counting the occurrences of type 3 and type 4 eventTypes
.但这只是返回每个
deviceID
的最小值和最大值,而不是计算类型 3 和类型 4 eventTypes
的出现次数。
I'm having trouble figuring out how to split the eventType
values into their own columns.我无法弄清楚如何将
eventType
值拆分为它们自己的列。
I've also tried:我也试过:
SELECT deviceId, COUNT(eventType)
FROM eventLog
WHERE eventType = 3
GROUP BY deviceId;
But that (obviously) only returns the count per deviceId for eventType 3 - and I need a column for eventType 3 AND one for eventType4.但是(显然)只返回 eventType 3 的每个 deviceId 的计数 - 我需要一个 eventType 3 的列和一个 eventType4 的列。
You can sum the cases in your select and filter in the having where those sums don't match.您可以对 select 中的案例求和,并在这些总和不匹配的地方进行过滤。
SELECT
deviceId,
SUM(CASE WHEN eventType = 3 THEN 1 ELSE 0 END) as type3Count,
SUM(CASE WHEN eventType = 4 THEN 1 ELSE 0 END) as type4Count
FROM
eventLog
WHERE
eventType IN(3,4)
GROUP BY
deviceId
HAVING
SUM(CASE WHEN eventType = 4 THEN 1 ELSE 0 END) <> SUM(CASE WHEN eventType = 3 THEN 1 ELSE 0 END)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.