dbTalk Databases Forums  

How do I use GROUP BY when I am using CASE?

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


Discuss How do I use GROUP BY when I am using CASE? in the comp.databases.ms-sqlserver forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
BobRoyAce
 
Posts: n/a

Default How do I use GROUP BY when I am using CASE? - 07-18-2011 , 09:40 PM






Let's say that I want to have a query like the following:

SELECT Field1, Field2,
CASE Field3
WHEN 1 THEN 'GOOD'
WHEN 2 THEN 'BAD'
ELSE 'UGLY'
END AS FieldResult,
SUM(Field4) AS TotalField4
FROM Table1
GROUP BY Field1, Field2, FieldResult

How do I accomplish something like this? The query above does not work
as it does not recognize a field called FieldResult.

I got it to work by changing the query as shown below, but I am
wondering if there is a smarter/better way to do it.

SELECT Field1, Field2,
CASE Field3
WHEN 1 THEN 'GOOD'
WHEN 2 THEN 'BAD'
ELSE 'UGLY'
END AS FieldResult,
SUM(Field4) AS TotalField4
FROM Table1
GROUP BY Field1, Field2, CASE Field3
WHEN 1 THEN 'GOOD'
WHEN 2 THEN 'BAD'
ELSE 'UGLY'
END

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

Default Re: How do I use GROUP BY when I am using CASE? - 07-19-2011 , 08:15 AM






you can try selecting from a result set, do all your manipulation via
CASE in the inner result set,, and save the SUM till you have the data
as you need it. then do the SUM and GROUP on the outer part.

SELECT Field1, Field2, FieldResult , SUM(Field4)
FROM(
SELECT Field1, Field2,
CASE Field3
WHEN 1 THEN 'GOOD'
WHEN 2 THEN 'BAD'
ELSE 'UGLY'
END AS FieldResult,
-- SUM(Field4) AS TotalField4
FROM Table1
) AS A
GROUP BY Field1, Field2, FieldResult

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.