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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Pivoting in SQL

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, type
From TableName
GROUP BY type

I get data like this:

Total Type
2 doc
4 pdf
5 xls


I 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]

Go to Top of Page

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, type
From tablename
GROUP BY type
)S
pivot (max(total) for type in ([doc],[pdf],[xls]))p

SELECT 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 xls
FROM
(
SELECT COUNT(*) AS Total, type
From tablename
GROUP BY type
)S
[/code]
Go to Top of Page

bklr
Master Smack Fu Yak Hacker

1693 Posts

Posted - 2009-06-04 : 00:47:50
check these links

http://sqlblogcasts.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

http://sqlblogcasts.com/blogs/madhivanan/archive/2007/08/27/dynamic-crosstab-with-multiple-pivot-columns.aspx
Go to Top of Page

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?
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2009-06-04 : 02:46:48
Refer the first link posted

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -