基于Or的计数不区分计数

时间:2012-09-26 20:29:27

标签: tsql

我的结果显示两个计数相同但应该有一些具有不同的计数,因为CarCode有时为空。

SELECT  distinct car.carKey,            
    car.Weight,
    car.CarCode,
    COUNT(car.carKey)OVER(PARTITION BY car.carKey) AS TotalCarKeyCount,
    COUNT(Case When (car.[Weight] IS not null) and (car.CarCode is null) as CarCountWithoutCode 
           then 0 
       else car.carKey End) OVER(PARTITION BY car.carKey) AS CarCount
from car

结果显示TotalCarKeyCountCarCountWithoutCode始终具有相同的计数,例如case语句不起作用。

2 个答案:

答案 0 :(得分:1)

听起来您可能想要使用SUM()代替:

SELECT  distinct car.carKey,            
    car.Weight,
    car.CarCode,
    COUNT(car.carKey)OVER(PARTITION BY car.carKey) AS TotalCarKeyCount,
    SUM(Case When (car.[Weight] IS not null) and (car.CarCode is null) as CarCountWithoutCode 
           then 0 else 1 End) OVER(PARTITION BY car.carKey) AS CarCount
from car

SQL Fiddle demo显示了使用COUNT()SUM()

之间的区别
create table test
(
  id int
);

insert into test values
(1), (null), (23), (4), (2);

select 
  count(case when id is null then 0 else id end) [count],
  sum(case when id is null then 0 else 1 end) [sum]
from test;

Count返回5并且Sum返回4.或者您可以更改COUNT()以使用nullnull值将被排除在最终count()

select 
  count(case when id is null then null else id end) [count],
  sum(case when id is null then 0 else 1 end) [sum]
from test;

您的查询将是:

SELECT  distinct car.carKey,            
    car.Weight,
    car.CarCode,
    COUNT(car.carKey)OVER(PARTITION BY car.carKey) AS TotalCarKeyCount,
    COUNT(Case When (car.[Weight] IS not null) and (car.CarCode is null) as CarCountWithoutCode 
           then null else 1 End) OVER(PARTITION BY car.carKey) AS CarCount
from car

答案 1 :(得分:0)

then 0更改为then null。零值被计算,空值不计算。