SQL 带 COUNT DISTINCT 的 case 语句分组
SQL group by case statement with COUNT DISTINCT
我在 SQL Server 2012 中的 table 如下所示:
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 丢失(但 Customer 名称已知)
- 并且存在 CustomerID 存在的情况(但缺少 Customer 名称)
期望的输出是:
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
无法更新 table 以删除 NULL 值。
这不是正确的做法。在 case statement
之外使用 Count
。
考虑到 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
试试这个:
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
我在 SQL Server 2012 中的 table 如下所示:
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 丢失(但 Customer 名称已知)
- 并且存在 CustomerID 存在的情况(但缺少 Customer 名称)
期望的输出是:
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
无法更新 table 以删除 NULL 值。
这不是正确的做法。在 case statement
之外使用 Count
。
考虑到 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
试试这个:
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