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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

query help

Status
Not open for further replies.

rotelmak

Programmer
Nov 29, 2004
31
0
0
MK

I have table with this records

product_id quantity color
1 10 red
1 20 black
1 30 green
1 40 red
1 50 black
2 60 black
2 70 green
2 80 black

I want with query to got this result

product_id red black green
1 50 70 30
2 0 140 70

There are only 3 colors (red, black, green)
 
This should do the trick:
Code:
[COLOR=blue]select[/color] product_id
, sum([COLOR=blue]case[/color] [COLOR=blue]when[/color] color = [COLOR=red]'red'[/color] [COLOR=blue]then[/color] quantity [COLOR=blue]else[/color] 0 [COLOR=blue]end[/color]) [COLOR=blue]as[/color] red
, sum([COLOR=blue]case[/color] [COLOR=blue]when[/color] color = [COLOR=red]'black'[/color] [COLOR=blue]then[/color] quantity [COLOR=blue]else[/color] 0 [COLOR=blue]end[/color]) [COLOR=blue]as[/color] black
, sum([COLOR=blue]case[/color] [COLOR=blue]when[/color] color = [COLOR=red]'green'[/color] [COLOR=blue]then[/color] quantity [COLOR=blue]else[/color] 0 [COLOR=blue]end[/color]) [COLOR=blue]as[/color] green
[COLOR=blue]from[/color] leTable
[COLOR=blue]group[/color] [COLOR=blue]by[/color] product_id

Basically you use the CASE statement to filter your sums by what color they are. Make sense?

HOpe it helps,

Alex

Ignorance of certain subjects is a great part of wisdom
 
Glad it helped :)

Ignorance of certain subjects is a great part of wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top