Hello I have a table like so:
Building Categories Properties
-----------------------------------------
Building250 Structure Steel
Building250 Security Access Card
Building250 Security Security Guard
Building250 Security Fire Alarm System
Building250 Security Sprinklered
Building250 Security Smoke or heat detectors
Building46 Structure Brick
Building46 Structure Steel
Building46 Walls Steel Stud
Building46 Walls Masonry
Building46 Washroom OwnSpace
Building46 Washroom Common
Building46 Security Access Card
Building46 Security Burglar Alarm
and I need to pivot it like so:
Building Structure Security Walls Washroom
----------------------------------------------------------------------------
Building250 Steel Access Card
Security Guard
Fire Alarm System
Sprinklered
heat detectors
Building46 Brick Access Card Steel Stud OwnSpace
Steel Burglar Alarm Masonry Common
Sprinklered
I tried SQL Pivot, but since it requires an aggregation, it returns only 1 property for a given category. Is there another way?
Here's my Pivot SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Category)
FROM Buildings
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Building, ' + @cols + ' from
(
SELECT Building, Category, Property, from Buildings
) x
pivot
(
min(Property)
for Category in (' + @cols + ')
) p '
execute(@query)
As you noted Pivot can do aggregation and while there are workarounds possible you can accomplish what you need without pivot with something like the following. You could also make it dynamic using the same method you would make a dynamic pivot.