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 |
|
drpkrupa
Yak Posting Veteran
74 Posts |
Posted - 2007-01-05 : 16:58:00
|
| I have a query return following rows.ID Type Count1 New 21 Old 12 new 13 old 54 old 24 extra 3I need result like thisID New Old Extra1 2 1 02 1 0 03 0 5 04 0 2 3The type can be grow (now all rows has max three column it can be four or five or six for id 5 or 10 or 15)How can i achive this |
|
|
snSQL
Master Smack Fu Yak Hacker
1837 Posts |
Posted - 2007-01-05 : 17:10:33
|
Can the number of types just keep on growing, or is the number fixed, but more than what you've given?If it will keep on growing then you need a cross-tab querySee here for SQL Server 2000 http://sqlteam.com/item.asp?ItemID=2955Or, see the PIVOT clause for SQL Server 2005If the number of types is fixed then you can do thisSELECT ID, CASE WHEN Type = 'New' THEN Count ELSE 0 END AS [New], CASE WHEN Type = 'Old' THEN Count ELSE 0 END AS [Old], CASE WHEN Type = 'Extra' THEN Count ELSE 0 END AS [Extra]FROM yourtable |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-01-05 : 18:27:41
|
| [code]SELECT ID, SUM(CASE WHEN Type = 'New' THEN Count ELSE 0 END) AS [New], SUM(CASE WHEN Type = 'Old' THEN Count ELSE 0 END) AS [Old], SUM(CASE WHEN Type = 'Extra' THEN Count ELSE 0 END) AS [Extra]FROM yourtableGROUP BY ID, ORDER BY ID[/code]Peter LarssonHelsingborg, Sweden |
 |
|
|
drpkrupa
Yak Posting Veteran
74 Posts |
Posted - 2007-01-05 : 23:45:06
|
| The type can grow by itselt. How can i make dynamic query so if type get increse the column can increase too. I dont want a hard code. Need help please. |
 |
|
|
snSQL
Master Smack Fu Yak Hacker
1837 Posts |
Posted - 2007-01-06 : 03:27:09
|
quote: Originally posted by drpkrupa The type can grow by itselt. How can i make dynamic query so if type get increse the column can increase too. I dont want a hard code. Need help please.
If it will keep on growing then you need a cross-tab querySee here for SQL Server 2000 http://sqlteam.com/item.asp?ItemID=2955Or, see the PIVOT clause for SQL Server 2005 |
 |
|
|
|
|
|
|
|