Pivot Query

I am trying to write a query to pivot this data.
Pivot.txt
LVL 1
progincAsked:
Who is Participating?
 
PortletPaulConnect With a Mentor Commented:
There are some unresolved issues in the following:
1. Including DeviceID in the final result is a problem - it produces too many rows
2. I have not found a way to provide zero instead of null in the final output
3. if I don't order the pivot headings it will be unpredictable (so different to expected)
4. I think there are errors in the expected results provided

* believe these are incorrect
Expected:
DeviceID 	DeviceName	Users	Customers   Vendors	SpecialAccess	Etc...
000091		MainOffice	  2	    1	       4              0        
000092		Office1		  0 	    2          0	       0 
000093		Office2		  0 	    0	       1  	       0
000094		Office3		  1*        1*         3               4 

so far achieved:
DEVICENAME	CUSTOMERS	SPECIALACCESS	USERS	VENDORS
MainOffice	1		(null)		2	4
Office1		2		(null)		(null)	(null)
Office2		(null)		(null)		(null)	1
Office3		2		4		2	3

Open in new window

The code to produce the above is this:
DECLARE @cols AS NVARCHAR(MAX)
DECLARE @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME([Group]) AS COLORD
            FROM OrigData
            ORDER BY COLORD
            FOR XML PATH('')
                   , TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT DeviceName, ' + @cols + ' from 
            (
                select
                      DeviceName
                    , [Group]
                    , case
                          when permission = 1 and pending = 0 then 1 
                          when permission = 1 and pending = 1 then 2 
                          when permission = 0 and pending = 0 then 3 
                          when permission = 0 and pending = 1 then 4 
                       end as lookupval
                from OrigData
           ) AS O
            pivot 
            (
                max(lookupval) for [Group] in (' + @cols + ')
            ) AS P'

execute(@query)
;

Open in new window

which can be seen/used at: http://sqlfiddle.com/#!3/dc920/41
{+ 2 edits, forgot to include issue #1, refined query slightly}
0
 
PortletPaulCommented:
could you spend some time explaining this?
Original Data

DeviceID 	DeviceName	Group			Permission 	Pending
000001		MainOffice	Users	  		  1		   1	 
000011		MainOffice	Customers	  	  1		   0	 
000021		MainOffice	Vendors	  	  	  0		   1	 
000002		Office1		Customers 		  1		   1
000003		Office2		Vendors 		  1		   0 
000004		Office3		SpecialAccess		  0		   1
000014		Office3		Users		  	  1		   1
000024		Office3		Customers		  1		   1
000034		Office3		Vendors		  	  0		   0



Pivot Data


DeviceID 	DeviceName	Users	Customers   Vendors	SpecialAccess	Etc...
000091		MainOffice	  2	    1	       4              0        
000092		Office1		  0 	    2          0	       0 
000093		Office2		  0 	    0	       1  	       0
000094		Office3		  1         1	       3	       4 


1 - Allowed & Not Pending
2 - Allowed & Pending
3 - Denied & Not Pending
4 - Denied & Pending

Open in new window

e.g. How do you arrive at DeviceID 000091,92,93,94 from that data?
What are the numbers under the pivot headings? a SUM()? a COUNT()? something else?
is it sum(Permission + Pending) perhaps?
does Etc. mean there is more headings?

What is the relevance of the last 4 codes?

are you expecting dynamic sql?
what version of sql server is this for?
0
 
progincAuthor Commented:
My apologies for not giving any details.

The deviceID can be ignored, I just need a unique identifier. The exiting query gives me this result in the first table. I need to change that so i get the result listed in the second table.

The pivot headings are not sum or count but uses the rule specified below the table. Allowed and Denied is from the Permissions column. The list of groups can be 5 or 10, but i need only the top 5.

MS Sql 2005
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
PortletPaulCommented:
thanks, still would like to know about the "etc." and if this needs to be dynamic

If there is a finite number of headings then it does not need to be dynamic of course.
0
 
progincAuthor Commented:
yes it has to be dynamic, there will be infinite "groups", however we need to list the first 5.
0
 
PortletPaulCommented:
oh dear, what does "first 5" mean to you?
i.e. how would the SQL know what you are thinking here?

nb: "TOP 5" could be totally wrong
0
 
progincAuthor Commented:
You are correct, there is no way to determine first 5, and no criteria to select the Top 5, best way would be to select all groups.
0
 
progincAuthor Commented:
This is much better than my own query, i don't need the deviceID in my result so this would work for me. I am trying to modify this query to get a 0 instead of null. Thanks for your help.
0
 
PortletPaulCommented:
good luck with that zero, had me stumped. tried isnull() in a variety of ways.
please let me know if you succeed (and how)?
0
 
PortletPaulCommented:
I have found the secret to this isnull() ... back soon
0
 
PortletPaulCommented:
being changed
0
 
PortletPaulCommented:
DEVICENAME	CUSTOMERS	SPECIALACCESS	USERS	VENDORS
MainOffice	1		0		2		4
Office1		2		0		0		0
Office2		0		0		0		1
Office3		2		4		2		3

Open in new window

here it is. simple when you think about it. the dynamically produce list of columns cannot be the same in the upper and lower portions of the pivot query. the select list must do the ISNULL() (of course!), but a different string is required for the pivot itself (which should be ordered). so, the amended code
DECLARE @cols   AS NVARCHAR(MAX)
DECLARE @incols AS NVARCHAR(MAX)
DECLARE @query  AS NVARCHAR(MAX)

-- formulate the select list with isnull(...,0) as [...] , this may not need to be ordered
SET @cols =   STUFF((SELECT distinct ', isnull(' + QUOTENAME([Group]) + ',0) as ' + QUOTENAME([Group])  AS COLORD
              FROM OrigData
              ORDER BY COLORD
              FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')

-- formulate the corresponding for [...] in, this needs to be ordered
SET @incols = STUFF((SELECT distinct ',' + QUOTENAME([Group]) AS COLORD
              FROM OrigData
              ORDER BY COLORD
              FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')

-- formulate the dynamic pivot query, using @cols and @incols
set @query = 'SELECT DeviceName, ' + @cols + ' from 
            (
                select
                      DeviceName
                    , [Group]
                    , case
                          when permission = 1 and pending = 0 then 1 
                          when permission = 1 and pending = 1 then 2 
                          when permission = 0 and pending = 0 then 3 
                          when permission = 0 and pending = 1 then 4 
                       end as lookupval
                from OrigData
           ) AS O
            pivot 
            (
                max(lookupval) for [Group] in (' + @incols + ')
            ) AS P'

-- perform the formulated query
execute(@query)
;

Open in new window

see this at: http://sqlfiddle.com/#!3/ff39e/1
0
All Courses

From novice to tech pro — start learning today.