0

我的结果显示两个计数相同,但应该有一些计数不同,因为 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

结果显示TotalCarKeyCount并且CarCountWithoutCode始终具有相同的计数,例如 case 语句不起作用或其他情况。

4

2 回答 2

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 演示COUNT()显示了 using和之间的区别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()要使用null的值,这些null值将在最终结果中排除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
于 2012-09-26T20:51:47.387 回答
0

将 更改then 0then null。零值被计算在内,空值不被计算在内。

于 2012-09-26T20:48:52.563 回答