根据 SQL 中的类型和日期计算不同的 ID
Count Distinct IDs against type and Date in SQL
我有 table 数据如下所示。我正在查找每个 TYPE
与 DATE
的总计数。
以上数据输出为:
我尝试了以下查询,但结果包含重复计数不止一次。
SELECT
DATE,
SUM(CASE WHEN TYPE = 'Existing' THEN 1 ELSE 0 END) AS "EXISTING",
SUM(CASE WHEN TYPE = 'New' THEN 1 ELSE 0 END) AS "NEW"
FROM
mytab
WHERE
DATE >= '2022-01-01'
GROUP BY
DATE ;
上述查询的输出:
一种方法是在子查询之上进行条件聚合,该子查询首先只获取与原始 table 不同的记录。
SELECT
DATE,
COUNT(CASE WHEN TYPE = 'Existing' THEN 1 END) AS "EXISTING",
COUNT(CASE WHEN TYPE = 'New' THEN 1 END) AS "NEW"
FROM (SELECT DISTINCT ID, TYPE, DATE FROM mytab) t
WHERE DATE >= '2022-01-01'
GROUP BY DATE;
未经测试,但也许是您想要的:
SELECT
DATE,
COUNT(DISTINCT CASE WHEN TYPE = 'Existing' THEN ID END) AS "EXISTING",
COUNT(DISTINCT CASE WHEN TYPE = 'New' THEN ID END) AS "NEW"
FROM
mytab
WHERE
DATE >= '2022-01-01'
GROUP BY
DATE ;
我有 table 数据如下所示。我正在查找每个 TYPE
与 DATE
的总计数。
以上数据输出为:
我尝试了以下查询,但结果包含重复计数不止一次。
SELECT
DATE,
SUM(CASE WHEN TYPE = 'Existing' THEN 1 ELSE 0 END) AS "EXISTING",
SUM(CASE WHEN TYPE = 'New' THEN 1 ELSE 0 END) AS "NEW"
FROM
mytab
WHERE
DATE >= '2022-01-01'
GROUP BY
DATE ;
上述查询的输出:
一种方法是在子查询之上进行条件聚合,该子查询首先只获取与原始 table 不同的记录。
SELECT
DATE,
COUNT(CASE WHEN TYPE = 'Existing' THEN 1 END) AS "EXISTING",
COUNT(CASE WHEN TYPE = 'New' THEN 1 END) AS "NEW"
FROM (SELECT DISTINCT ID, TYPE, DATE FROM mytab) t
WHERE DATE >= '2022-01-01'
GROUP BY DATE;
未经测试,但也许是您想要的:
SELECT
DATE,
COUNT(DISTINCT CASE WHEN TYPE = 'Existing' THEN ID END) AS "EXISTING",
COUNT(DISTINCT CASE WHEN TYPE = 'New' THEN ID END) AS "NEW"
FROM
mytab
WHERE
DATE >= '2022-01-01'
GROUP BY
DATE ;