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.
| Author |
Topic |
|
paulodeleo
Starting Member
2 Posts |
Posted - 2002-02-25 : 15:57:07
|
| Hi,I have a table like this:product_name product_color product_total ------------ ------------- -------------prod1 Blue 1 prod1 Red 2prod2 Blue 2prod2 Red 4prod3 Blue 5How do i get the same data, but in that format:product_name blue_products red_products total ------------ ------------- ------------ -----prod1 1 2 3 prod2 2 4 6 prod3 5 0 5 Thanks in advance,Paul. |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2002-02-25 : 16:09:23
|
| Use the CASE statement to create a cross-tab:SELECT product_name,Sum(CASE product_color WHEN 'Blue' THEN product_total ELSE 0 END) Blue_Products, Sum(CASE product_color WHEN 'Red' THEN product_total ELSE 0 END) Red_Products, Sum(product_total) TotalFROM product_tableGROUP BY product_nameYou can add extra CASE statements for additional colors. Search SQL Team for "cross tab" or "pivot table" and you'll get several articles on cross-tab methods. |
 |
|
|
jbkayne
Posting Yak Master
100 Posts |
Posted - 2002-02-25 : 16:18:03
|
| I like Rob's solution better, but you could also do it this way:select distinct product_name , isnull((select product_total from Products where product_color = 'blue' and product_name=prod.product_name),0) as blue_products , isnull((select product_total from Products where product_color = 'red' and product_name=prod.product_name),0) as red_products , isnull((select product_total from Products where product_color = 'blue' and product_name=prod.product_name),0) + isnull((select product_total from Products where product_color = 'red' and product_name=prod.product_name),0) as totalfrom Products as Prod |
 |
|
|
paulodeleo
Starting Member
2 Posts |
Posted - 2002-02-25 : 16:28:42
|
| Thanks very, very much guys! |
 |
|
|
jvolpe
Starting Member
2 Posts |
Posted - 2005-09-01 : 11:42:53
|
| One other question. Let's say you want to pivot this info...Name EmailJason V jason.volpe@x.comJason V jason.volpe@google.comJason V jason.volpe@msn.comHow do you get the email addresses into Email1 Email2 Email3, etc columns without knowing the previous email for each column. I'm wanting to do this in a view. |
 |
|
|
|
|
|
|
|