来自CTE的多个COUNT(DISTINCT)

时间:2018-10-04 04:35:57

标签: sql-server tsql sql-server-2012 count common-table-expression

这是针对SQL Server 2012:我的CTE中的数据子集看起来像这样:

Employee | OrderID | OrderType
---------+---------+----------
Kala     | 321111  | 953
Paul     | 321222  | 1026
Don      | 321333  | 1026
Don      | 321333  | 953
Kala     | 321444  | 953

我想要以下结果:

Employee | 953_Order_Count | 1026_Order_Count
---------+-----------------+-----------------
Kala     |        2        |    0
Don      |        1        |    1
Paul     |        0        |    1

当我跑步时,可以验证我想要的东西是否存在:

SELECT 
    Employee,
    OrderType,
    COUNT(DISTINCT OrderID) AS 'Count'
FROM
    CTE
GROUP BY 
    employee, ordertype

返回以下结果:

Employee | OrderType | Count
---------+-----------+------
Kala     | 953       | 1
Paul     | 1026      | 1
Don      | 1026      | 1
Don      | 953       | 1

关闭,但不够关闭。所以我跑:

SELECT 
    Employee,
    COUNT(DISTINCT OrderID) AS 'Total_Orders',
    COUNT(DISTINCT (CASE WHEN OrderType = 1026 THEN OrderID END)) AS '1026_Order_Count',
    COUNT(DISTINCT(CASE WHEN OrderType = 953 THEN OrderID END)) AS '953_Order_Count'
FROM
    CTE
GROUP BY 
    Employee

结果是第一个准确的“计数”,但其余的返回0。如果这不是CTE,则将使用递归语句。

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

只需使用条件聚合:

SELECT
    Employee,
    COUNT(CASE WHEN OrderType = 953  THEN 1 END) AS [953_Order_Count],
    COUNT(CASE WHEN OrderType = 1026 THEN 1 END) AS [1026_Order_Count]
FROM CTE
GROUP BY
    Employee;

enter image description here

Demo

例如,953计数在上面的工作方式是:当订单类型为953时为1,而当订单类型不是953时为NULL(隐式ELSE值)。COUNT默认情况下会忽略NULL,因此它只计算953个订单。

答案 1 :(得分:0)

蒂姆的答案看起来不错。您还可以使用PIVOT:

; with cte (Employee, OrderID, OrderType)
as
(
    select 'Kala', 321111, 953
union select 'Paul', 321222, 1026
union select 'Don', 321333, 1026
union select 'Don', 321333, 953
union select 'Kala', 321444, 953
)
select Employee, [953] as [953_Order_Count],[1026] as [1026_Order_Count]
from 
    (
        select Employee, OrderType from cte ) as sourceData
pivot
(
    count(OrderType)
    for OrderType
    in ([953],[1026])
) as myPivot

如果要基于OrderType列中的一组可用值来创建动态列,则可以动态构建查询。有关示例,请参见@Taryn对Understanding PIVOT function in T-SQL的回答。