dbTalk Databases Forums  

Displaying Data Across when data goes down! Has to be easy!

comp.databases.ms-sqlserver comp.databases.ms-sqlserver


Discuss Displaying Data Across when data goes down! Has to be easy! in the comp.databases.ms-sqlserver forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
gwhite1@kc.rr.com
 
Posts: n/a

Default Displaying Data Across when data goes down! Has to be easy! - 05-02-2007 , 07:04 PM






I have a table with:

Name, Qtr, Amount
Tom, 1, 100
Bob, 1, 123
Tom, 2, 234
Bob, 2, 456
Steve, 1, 565
Steve, 2, 898

I want the query to return:

Name, Qtr 1 Amount, Qtr 2 Amount
Bob 123 456
Steve 565 898
Tom 100 234

I can't seem to figure this out! Any help would be appreciated!!
Sheila


Reply With Quote
  #2  
Old   
ZeldorBlat
 
Posts: n/a

Default Re: Displaying Data Across when data goes down! Has to be easy! - 05-02-2007 , 07:36 PM






On May 2, 8:04 pm, gwhi... (AT) kc (DOT) rr.com wrote:
Quote:
I have a table with:

Name, Qtr, Amount
Tom, 1, 100
Bob, 1, 123
Tom, 2, 234
Bob, 2, 456
Steve, 1, 565
Steve, 2, 898

I want the query to return:

Name, Qtr 1 Amount, Qtr 2 Amount
Bob 123 456
Steve 565 898
Tom 100 234

I can't seem to figure this out! Any help would be appreciated!!
Sheila
Search this newsgroup for the word "crosstab."



Reply With Quote
  #3  
Old   
Plamen Ratchev
 
Posts: n/a

Default Re: Displaying Data Across when data goes down! Has to be easy! - 05-02-2007 , 09:38 PM



Here is one way to do this:

SELECT Name,
SUM(CASE WHEN Qtr = 1
THEN Amount
ELSE 0 END) AS 'Qtr 1 Amount',
SUM(CASE WHEN Qtr = 2
THEN Amount
ELSE 0 END) AS 'Qtr 2 Amount'
FROM Foo
GROUP BY Name;


In SQL Server 2005 it can be done with the PIVOT operator:

SELECT Name,
[1] AS 'Qtr 1 Amount',
[2] AS 'Qtr 2 Amount'
FROM Foo
PIVOT
(SUM(Amount) FOR Qtr IN ([1], [2])) AS P;


HTH,

Plamen Ratchev
http://www.SQLStudio.com




Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.