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 |
|
valgrom
Starting Member
2 Posts |
Posted - 2009-06-04 : 00:28:53
|
| I am relatively new to SQL so forgive the ignorance.I have a table in which I've executed a query like this:SELECT COUNT(*) AS Total, typeFrom TableNameGROUP BY typeI get data like this:Total Type2 doc4 pdf5 xlsI would like to pivot this table to show the "type" in row one accross various columns and "total" in row two across various columns.Can anyone offer assistance?Thank you,Mike |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2009-06-04 : 00:30:08
|
if you are using SQL Server 2005, you can use the PIVOT keyword KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
Posted - 2009-06-04 : 00:43:49
|
| [code]select [doc],[pdf],[xls]from (SELECT COUNT(*) AS Total, typeFrom tablenameGROUP BY type)Spivot (max(total) for type in ([doc],[pdf],[xls]))pSELECT max(CASE WHEN [type] = 'doc' THEN total END )AS doc,max(CASE WHEN [type] = 'pdf' THEN total END )AS pdf,max(CASE WHEN [type] = 'xls' THEN total END )AS xlsFROM (SELECT COUNT(*) AS Total, typeFrom tablenameGROUP BY type)S[/code] |
 |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
|
|
valgrom
Starting Member
2 Posts |
Posted - 2009-06-04 : 01:39:18
|
| Well, I'm not afraid to say I'm totally lost. Since I just touched SQL for the first time yesterday I'm not at all familiar with the terminology or what the keywords do.blkr:Thanks for the links and the code. My problem with the code is that there could be dozens of "Document Types" so it would be hard to list them all in the query.I've been reading a lot of threads on Pivot but I just don't understand how it works. The code you suggested above, will it work if document types are added to the database that are not listed there? |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2009-06-04 : 02:46:48
|
| Refer the first link postedMadhivananFailing to plan is Planning to fail |
 |
|
|
|
|
|
|
|