SQL Fiddle
MS SQL Server 2008的架構設置:
DECLARE @Table TABLE (UserID INT, SettingID INT, Value INT)
INSERT INTO @Table VALUES
(1 , 10 ,0),
(1 , 11 ,1),
(1 , 14 ,0),
(2 , 10 ,1),
(2 , 13 ,1)
查詢1:
SELECT UserID
,COALESCE( Setting10 , 'not set') Setting10
,COALESCE( Setting11 , 'not set') Setting11
,COALESCE( Setting13 , 'not set') Setting13
,COALESCE( Setting14 , 'not set') Setting14
FROM (
SELECT UserID
, 'Setting' + CAST(SettingID AS VARCHAR(10)) AS Settings
,CASE Value WHEN 0 THEN 'off'
WHEN 1 THEN 'on'
END AS Value
FROM @Table
) t
PIVOT (MAX(Value)
FOR Settings
IN (Setting10 , Setting11 , Setting13 , Setting14)
)p
Results:
| UserID | Setting10 | Setting11 | Setting13 | Setting14 |
|--------|-----------|-----------|-----------|-----------|
| 1 | off | on | not set | off |
| 2 | on | not set | on | not set |