Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Interesting interview questions that stumped me.

Author  Topic 

nathans
Aged Yak Warrior

938 Posts

Posted - 2005-03-14 : 15:04:51
Given these tables:


CREATE TABLE [dbo].[robdt] (
[id] [int] NOT NULL ,
[gamedate] [datetime] NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[robtm] (
[id] [int] NOT NULL ,
[name] [varchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[robtm_gm] (
[id] [int] NOT NULL ,
[game_id] [int] NULL ,
[team_id] [int] NULL ,
[score] [int] NULL
) ON [PRIMARY]
GO
INSERT 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 robtm
INSERT 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_gm
INSERT 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!





spirit1
Cybernetic Yak Master

11752 Posts

Posted - 2005-03-14 : 15:08:17
will this help?

http://www.sqlteam.com/item.asp?ItemID=12654

Go with the flow & have fun! Else fight the flow
Go to Top of Page

TimS
Posting Yak Master

198 Posts

Posted - 2005-03-14 : 15:34:26

SELECT nm.name AS [team_name],
SUM(CASE WHEN tm1.score > tm2.score THEN 1 ELSE 0 END) AS [Wins],
SUM(CASE WHEN tm1.score < tm2.score THEN 1 ELSE 0 END) AS [Losses],
SUM(CASE WHEN tm1.score = tm2.score THEN 1 ELSE 0 END) AS [Ties]
FROM #robtm_gm tm1
JOIN #robtm_gm tm2 ON tm1.game_id = tm2.game_id AND tm1.team_id <> tm2.team_id
JOIN #robtm nm ON tm1.team_id = nm.id
GROUP BY nm.name

Tim S
Go to Top of Page

nathans
Aged Yak Warrior

938 Posts

Posted - 2005-03-14 : 17:02:18
nice work Tim. Exactly what I was looking for.
Go to Top of Page
   

- Advertisement -