我在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
我想知道每个销售日期的独特客户数量,考虑到:
所需的输出是:
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值。
答案 0 :(得分:1)
这不是正确的做法。在Count
之外使用case statement
。
考虑CustomerID
是Integer
列。试试这个
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