繁体   English   中英

SQL运行count(*)和count(*)group by返回不同的行数

[英]SQL running a count(*) and count(*) group by returns differnet number of rows

这很奇怪,可以说我在SQL server有一个名为dbo.internetquotes的表。

我想获取一个月内的报价总数,并按称为quotetype的列进行细分。

我运行查询:

select count(*) from dbo.internetquotes
where quotedate between '2014/03/01' and '2014/04/01';

并返回20k。

现在我运行查询

select count(*), quotetype from dbo.internetquotes
where quotedate between '2014/03/01' and '2014/04/01'
group by quotetype;

并返回每个报价类型的计数。 但是,当我对第二个查询的计数求和时,数字不等于20k(略小)。 我的想法是,列引用类型中可能有空值,但是运行select * where quotetype = null返回0行。

出现差异的原因是什么?

当任何与聚合不匹配的东西时,只需考虑三个值-TRUE,FALSE和UNKNOWN。

汇总时,您可能会放弃NULL(UNKNOWN)。

另外,在处理日期时,请使用>和<。

不良习惯:错误处理日期/范围查询

-- 1 - Skip nulls
select 
    count(*) as Total
from 
    dbo.internetquotes
where 
    quotedate >= '20140301' and 
    quotedate < '20140401' and
    quotetype is not null

-- 2 - Skip nulls
select 
    quotetype, count(*) as total
from 
    dbo.internetquotes
where 
    quotedate >= '20140301' and 
    quotedate < '20140401' and
    quotetype is not null
group by 
    quotetype;

这两个查询应具有相同的计数。 祝好运。

只需使用Adventure Works并尝试这些查询

-- 31465
select count(*) from [Sales].[SalesOrderHeader]

-- Group by person 
select SalesPersonID, count(*) as total
into #temp
from [Sales].[SalesOrderHeader] 
group  by SalesPersonID

-- 18 rows for a total count of 31465
select sum(total) as grand from #temp

空值将按分组并显示为一行。 我从不轻视。 但是日期问题可能会丢失数据。 我拥护!

我考虑了一会儿,我认为您有重复的行或重复的quotedate。

你可以运行类似的东西吗?

select count(distinct quotedate) from dbo.internetquotes
where quotedate between '2014/03/01' and '2014/04/01';

与第二个查询的总和进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM