带有COUNT DISTINCT的SQL分组语句

时间:2015-02-04 17:16:39

标签: sql sql-server-2012

我在SQL Server 2012中的表格如下所示:

SaleDate    CustomerID    Customer    
2014-03-01     NULL        George    
2014-03-01     NULL        John        
2014-03-01     125         Emy    
2014-04-01     126         Natasha    
2014-04-01     127         NULL   
2014-05-01     128         Jack

我想知道每个销售日期的独特客户数量,考虑到:

  • 有时 CustomerID 缺失(但客户名称已知)
  • 并且存在 CustomerID 存在的情况(但缺少客户名称)

所需的输出是:

SaleDate       UniqueCustomers
2014-03-01          3
2014-04-01          2
2014-05-01          1

我尝试了这个查询,但是 - 当然 - 我收到以下错误:不能在用于GROUP BY子句列表的表达式中使用聚合或子查询

SELECT SaleDate,
       CASE
           WHEN Customer IS NULL THEN COUNT(DISTINCT CustomerID)
           ELSE COUNT(DISTINCT Customer)
       END AS "UniqueCustomers"
FROM TableA
GROUP BY SaleDate,
         CASE
             WHEN Customer IS NULL THEN COUNT(DISTINCT CustomerID)
             ELSE COUNT(DISTINCT Customer)
         END

无法更新表以消除NULL值。

2 个答案:

答案 0 :(得分:1)

这不是正确的做法。在Count之外使用case statement

考虑CustomerIDInteger列。试试这个

SELECT SaleDate,
       Count(DISTINCT CASE
                        WHEN Customer IS NULL THEN CONVERT(VARCHAR(50), CustomerID)
                        ELSE Customer
                      END) AS UniqueCustomers
FROM   Yourtable
GROUP  BY SaleDate 

答案 1 :(得分:0)

试试这个:

SELECT PreparedTable.SaleDate, SUM(PreparedTable.Uniques)
FROM
    (
    SELECT SaleDate, COUNT(DISTINCT CustomerID) as Uniques
        FROM TableA
        GROUP BY SaleDate
    UNION ALL
    SELECT SaleDate, COUNT(DISTINCT Customer)
        FROM TableA
        WHERE CustomerID is null
        GROUP BY SaleDate
    ) PreparedTable

GROUP BY SaleDate