Search code examples
sqlt-sqlviewdistinct-values

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.

I am referencing this answer since it is looking for a similar outcome Count the occurrences of DISTINCT values

I have tried this expression but when executed, it returns the same number in both case columns

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 ; 

Solution

  • 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