显示结果的SQL查询等于0不满足where子句

时间:2017-07-12 09:35:18

标签: sql sql-server

我有以下SQL查询。球员'贾德'没有PlaceFinished = 4的条目。

select PlaceFinished, count(PlaceFinished) as PlaceCount , sum (PointsAwarded) as Points 
from Teams_tbl T
where Player = 'Judd' and PlaceFinished is not NULL and PlaceFinished in (1,2,3,4) 
group by PlaceFinished

目前的结果是

PlaceFinished   PlaceCount
1               6
2               2
3               6

我希望它显示:

PlaceFinished   PlaceCount
1               6
2               2
3               6
4               0

我尝试使用Left Outer Join创建一个虚拟表,但结果是相同的

Declare @Places Table(
place int
)

Insert into @Places
select distinct PlaceFinished from Teams_tbl

select p.place, count(PlaceFinished) as PlaceCount , sum (PointsAwarded) as Points from Teams_tbl T
Left Outer Join @Places P
on T.PlaceFinished = p.place
where Player = 'Judd' and PlaceFinished is not NULL group by p.place

2 个答案:

答案 0 :(得分:2)

如果你知道表中存在所有PlaceFinished值,无论玩家如何,你都可以进行条件聚合:

select PlaceFinished,
       count(case when Player = 'Judd' then 1 end) as PlaceCount,
       sum(case when Player = 'Judd' then PointsAwarded else 0 end) as Points 
from Teams_tbl T
where PlaceFinished in (1,2,3,4) 
group by PlaceFinished

答案 1 :(得分:0)

正确加入,因为你正在寻找一个没有一行完成的地方(第四个),因为贾德从来没有排在第四位。 PlaceFinished不会过滤掉玩家从未进入的所有地方,所以要摆脱它。此外,使用派生表过滤Judd,以便连接保持在外部。其他一切都很好: - )

select p.place, 
       count(PlaceFinished) as PlaceCount , 
       sum (PointsAwarded) as Points
from 
(Select placefinished as ..., FROM Teams_tbl Where Player='Judd') T
 Right Outer Join 
 @Places P
 on T.PlaceFinished = p.place 
 group by p.place