【发布时间】:2013-01-14 06:16:07
【问题描述】:
我正在 SQL Server 中运行查询,以按澳大利亚州统计我们数据库中存在的唯一电子邮件地址的数量。但是,当我尝试核对这些数字以确保它们正确时,我注意到了一个差异,这让我认为我的查询不正确。以下是我用来协调数字和实际结果的查询:
/** Count the total number of active members (status=1) since last night **/
SELECT count(distinct(email)) Total FROM [member] WHERE status = 1
AND (created_datetime <= '2013-01-11' OR created_datetime IS NULL)
/** RESULT: 8958 **/
/** Count the number of active members (status=1) who live in Victoria since last night **/
SELECT count(distinct(email)) Total FROM [member] WHERE status = 1
AND (created_datetime <= '2013-01-11' OR created_datetime IS NULL)
AND [state] = 'vic'
/** RESULT: 7545 **/
/** Count the number of active members (status=1) who don't live in Victoria since last night **/
SELECT count(distinct(email)) Total FROM [member] WHERE status = 1
AND (created_datetime <= '2013-01-11' OR created_datetime IS NULL)
AND [state] <> 'vic'
/** RESULT:1446 **/
/** Add the two results to see how they compare to the total **/
SELECT 7545+1446
/** RESULT:8991 **/
您会注意到不同电子邮件的总数为 8958 封,但如果您将居住在维多利亚州的电子邮件和未居住在维多利亚州的电子邮件相加,则数字为 8991,这是不同的。我是否错误地使用了 count distinct 功能?
【问题讨论】:
-
<= '2013-01-10 23:59:59'- 所以您不想包含在一天的最后一秒发生的任何事情?几乎总是更好(使用日期查询)为期间使用专有端点 - 例如< '20130111'. -
好点。我已经更新了查询,我将在上面编辑我的问题
标签: sql sql-server count distinct