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 |
|
Ziggadebo
Starting Member
20 Posts |
Posted - 2011-04-18 : 09:04:30
|
| I'm trying to breakdown some data held in table by using the sum function, I then want the next column to show a subset of the data returned by the first sum. This is much more easily explained by way of an example.Here is my original table called 'whatanimals':Animal Qty Ownerdog 2 jimcat 1 bobmouse 1 bettyhamster 2 bobbydog 2 billdog 3 brianNow my first query would beselect Animal,sum(Qty) from whatanimalsgroup by Animalwhich givesAnimal Qtydog 7cat 1mouse 1hamster 2What I then want to add to my results are extra columns, representing the number of animals by Ownerso i would haveAnimal Qty Jim Bobdog 7 2 0cat 1 0 1mouse 1 0 0hamster 2 0 0fish 0 0 0and so on, I'm not sure the best way to construct this (or anyway if I'm honest) I've tried fiddling around with case statements but am getting knowhere fast, could someone please point me in the right direction?Many Thanks |
|
|
nigelrivett
Master Smack Fu Yak Hacker
3385 Posts |
Posted - 2011-04-18 : 09:27:21
|
| select Animal,sum(Qty), jim = SUM(case when owner = 'jim' then qty else 0 end), Bob = SUM(case when owner = 'Bob' then qty else 0 end)from whatanimalsgroup by Animal==========================================Cursors are useful if you don't know sql.SSIS can be used in a similar way.Beer is not cold and it isn't fizzy. |
 |
|
|
Ziggadebo
Starting Member
20 Posts |
Posted - 2011-04-18 : 09:58:12
|
quote: Originally posted by nigelrivett select Animal,sum(Qty), jim = SUM(case when owner = 'jim' then qty else 0 end), Bob = SUM(case when owner = 'Bob' then qty else 0 end)from whatanimalsgroup by Animal==========================================Cursors are useful if you don't know sql.SSIS can be used in a similar way.Beer is not cold and it isn't fizzy.
Thanks very much, thats exactly what I've been trying to do. This really helps thanks again. |
 |
|
|
|
|
|
|
|