简体   繁体   English

CASE 表达式中的计数和 GROUP 值

[英]Count and GROUP values from a CASE expression

Trying to count the total number of wins and total times a horse finished in the top 6 and GROUP by the order of favouritism in a horse racing market.试图按照赛马市场中的偏好顺序计算一匹马在前 6 名和GROUP的总获胜次数和总次数。

I am referencing this answer since it is looking for a similar outcome Count the occurrences of DISTINCT values我正在参考这个答案,因为它正在寻找类似的结果计算 DISTINCT 值的出现次数

I have tried this expression but when executed, it returns the same number in both case columns我已经尝试过这个表达式,但是在执行时,它在两个 case 列中返回相同的数字

ie; IE;

SPFav   WinsByFavouritism   PlaceByFavouritism
1       4143                4143
2       3963                3963
3       3853                3853

This is the code I am running - what is causing this?这是我正在运行的代码 - 是什么导致了这个?

SELECT SPFav, 

COUNT(CASE WHEN FinishingPosition = 1 THEN 1 ELSE 0 END) as WinsByFavouritism,
COUNT(CASE WHEN FinishingPosition <= 6 THEN 1 ELSE 0 END) as PlaceByFavouritism

FROM [NRaceHistory].[dbo].[EachWayBetting]

GROUP BY SPFav 

ORDER BY SPFav ; 

Working with the first comment this would give the following possible solution.使用第一个评论,这将提供以下可能的解决方案。

Sample data样本数据

create table EachWayBetting
(
  SPFav int,
  FinishingPosition int
);

insert into EachWayBetting (SPFav, FinishingPosition) values
(1, 1),
(1, 2),
(1, 2),
(1, 9),
(2, 7),
(2, 8),
(2, 2),
(2, 1);

Solution解决方案

SELECT SPFav,
       COUNT(CASE WHEN FinishingPosition = 1 THEN 1 END) as WinsByFavouritism,
       COUNT(CASE WHEN FinishingPosition <= 6 THEN 1 END) as PlaceByFavouritism
FROM EachWayBetting
GROUP BY SPFav
ORDER BY SPFav

Result结果

SPFav WinsByFavouritism PlaceByFavouritism
----- ----------------- ------------------
1     1                 3
2     1                 2

Fiddle 小提琴

I believe you should replace COUNT in your query with SUM.我相信您应该用 SUM 替换查询中的 COUNT。 ie it should be:即它应该是:

SELECT SPFav, 
       SUM(CASE WHEN FinishingPosition = 1 THEN 1 ELSE 0 END) as WinsByFavouritism,
       SUM(CASE WHEN FinishingPosition <= 6 THEN 1 ELSE 0 END) as PlaceByFavouritism
FROM [NRaceHistory].[dbo].[EachWayBetting]
GROUP BY SPFav 
ORDER BY SPFav;

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

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