sql server - How to calculate percentages in tsql using a group by query? -
i have table lists results sport , start , end dates , win/loss result. need calculate percentage of wins per sport per season_start. table:
table1 ****** id sport won playerid season_start season_end updated_date --- ----- ---- -------- ------------ ------------ ------------ 1 rugby y kato23 2016-01-01 2016-01-31 2016-02-01 2 rugby y king54 2016-01-01 2016-01-31 2016-02-01 3 rugby n robby1 2016-03-01 2016-03-28 2016-04-01 4 rugby y kelly2 2016-03-01 2016-03-28 2016-04-01 5 soccer y kato23 2016-01-01 2016-01-31 2016-02-01 6 soccer y jeri44 2016-01-01 2016-01-31 2016-02-01 7 soccer n matt24 2016-06-01 2016-06-30 2016-07-01 8 tennis y kray43 2016-01-01 2016-01-31 2016-02-01 9 tennis y jeri44 2016-01-01 2016-01-31 2016-02-01 10 tennis n jeri44 2016-01-01 2016-01-31 2016-02-01
so i'd run query produces following result:
sport season_start success_percent ----- ------------ --------------- rugby 2016-01-01 100.00 rugby 2016-03-01 50.00 soccer 2016-01-01 100.00 soccer 2016-06-01 0.00 tennis 2016-01-01 66.66
i tried :
select sport,won, season_start, count(sport) sportcount table1 won = 'y' group sport, won, season_start
but give me entire count not actual success percent. tried using case statement i'm not tsql, or using 'sum' tally wins , losses , calculate win percentage out of total.
can provide tsql query this?
you can use conditional counts this:
select sport, season_start, sportcount = count(case when won = 'y' 'x' end) * 100.0 / count(*) table1 group sport, season_start