将多个计数分组,每行代表一个ID

时间:2010-10-12 17:57:10

标签: sql sql-server pivot

我有一个记录活动的表。它有一个int活动列,指示它是什么类型的活动,以及一个相应的admin_id,指示哪个管理员执行了该操作。表中的每一行代表一个操作,因此,例如,管理员将取消用户的帐户,并且将创建具有该admin的id和activity = [int表示取消]的行。我需要一种方法来选择一个结果,该结果将每个管理员的活动分组,使得与管理员相对应的行将具有每个活动的#

结果看起来像

admin_id | numActivated | numCanceled | numRenewed
1          1              1             2
2          1              3             0

numActivated,numCanceled和numRenewed都来自每个活动的计数。

这就是原始表格的样子:

admin_id | activity ...
1          2
1          1
1          3
1          3
2          2
2          2
2          2
2          1

(活动1:激活,2:取消,3:续订)

由于

2 个答案:

答案 0 :(得分:3)

这应该做你要求的:

select admin_id,
       sum(case when activity = 1 then 1 else 0 end) as numActivated,
       sum(case when activity = 2 then 1 else 0 end) as numCanceled,
       sum(case when activity = 3 then 1 else 0 end) as numRenewed
    from YourTable
    group by admin_id

答案 1 :(得分:0)

这应该这样做:

SELECT
    T.admin_id,
    sum(T.activate) AS numActivated,
    sum(T.canceled) AS numCanceled,
    sum(T.renew) AS numRenewed
FROM (
    SELECT
        admin_id,
        CASE activity WHEN 1 THEN 1 ELSE 0 END AS activate,
        CASE activity WHEN 2 THEN 1 ELSE 0 END AS canceled,
        CASE activity WHEN 3 THEN 1 ELSE 0 END AS renew
    FROM Table
) AS T
GROUP BY T.admin_id