Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Custom Grouping multiple values 1

Status
Not open for further replies.

briesen

Technical User
May 13, 2008
24
US
I'm doing an SQL query where my first field has six different values.

Theoretically, they are Blue, Green, Red, Yellow, Orange, Purple

Is it possible to force them to group two or more colors together?

For example, I want Blue and Green to group together, Red and Yellow to Group together, and Orange and Purple to group together so the aggregate values add up in each group.

I tried this, but it still keeps them separate if I put an alias so I know it doesn't work.

Code:
SELECT
CASE
WHEN vtr.Color IN ('Blue', 'Green') THEN 'A' 
WHEN vtr.Color IN ('Red', 'Yellow') THEN 'B'
WHEN vtr.Color IN ('Orange', 'Purple') THEN 'C'
ELSE vtr.Color END AS [Color]

Thanks!
 
Use a derived table, or repeat your case statement in the GROUP BY clause. Here's a derived table example.

Code:
SELECT [Color],
SUM(SomeValueColumnExample) AS TheValue
FROM

(SELECT
CASE
WHEN vtr.Color IN ('Blue', 'Green') THEN 'A'
WHEN vtr.Color IN ('Red', 'Yellow') THEN 'B'
WHEN vtr.Color IN ('Orange', 'Purple') THEN 'C'
ELSE vtr.Color END AS [Color],
SomeValueColumnExample
FROM YourTableExample) x

GROUP BY [Color]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top