Given these tables:CREATE TABLE [dbo].[robdt] ( [id] [int] NOT NULL , [gamedate] [datetime] NULL ) ON [PRIMARY]GOCREATE TABLE [dbo].[robtm] ( [id] [int] NOT NULL , [name] [varchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) ON [PRIMARY]GOCREATE TABLE [dbo].[robtm_gm] ( [id] [int] NOT NULL , [game_id] [int] NULL , [team_id] [int] NULL , [score] [int] NULL ) ON [PRIMARY]GOINSERT INTO robdt VALUES(1,'08/04/2002 00:00')INSERT INTO robdt VALUES(2,'07/05/2002 00:00')INSERT INTO robdt VALUES(3,'10/06/2002 00:00')INSERT INTO robdt VALUES(4, '09/09/2002 00:00')INSERT INTO robdt VALUES(5, '11/15/2002 00:00')--insert into robtmINSERT INTO robtm VALUES (1, 'Reds')INSERT INTO robtm VALUES (2, 'Orioles')INSERT INTO robtm VALUES (3, 'Red Sox')INSERT INTO robtm VALUES (4, 'Padres')--insert robtm_gmINSERT INTO robtm_gm VALUES(1,1,1,4)INSERT INTO robtm_gm VALUES(2,1,3,4)INSERT INTO robtm_gm VALUES(3,2,2,1)INSERT INTO robtm_gm VALUES(4,2,3,6)INSERT INTO robtm_gm VALUES(5,3,4,21)INSERT INTO robtm_gm VALUES(6,3,1,8)INSERT INTO robtm_gm VALUES(7,4,2,2)INSERT INTO robtm_gm VALUES(8,4,1,10)
How can we write a query to return the following resultset in one select?[team_name] [Wins] [Losses] [Ties]
I want to write the query using a case like so:When the team's score is greater than the SUM(game_score)/2 then WIN. When it is less, then LOSS. When its equal, then TIE.But I cant get it in one SELECT.SOmething like:SELECT t.[name], SUM(CASE WHEN t.id = g.team_id AND g.score > SUM(g.score)/2 THEN 1 ELSE 0 END) AS 'Wins', 'Losses' AS 'Losses', 'Ties' AS 'Ties'FROM robtm t
Anyone help out on this? Thanks!