0

私の結果は両方のカウントが同じであることを示していますが、CarCodeがnullになることがあるため、カウントが異なるものもあるはずです。

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

結果が表示され、caseステートメントが機能していないなどのようTotalCarKeyCountCarCountWithoutCode常に同じカウントで表示されます。

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

COUNT()との使用の違いを示すSQL Fiddle デモ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 に答える