2015-10-01 87 views
0

我有3列的SQL Server表:UserID, SettingID, SettingValueSQL服務器:查詢轉動,並顯示沒有設定值

UserID | SettingID | Value 
1  | 10  |0 
1  | 11  |1 
1  | 14  |0 
2  | 10  |1 
2  | 13  |1 
  1. 需要轉換成列的每個設置ID
  2. 可以是有一個設置ID沒有行 - >要搶非exisitng而顯示爲「未設置」

期望的結果:

UserID | Setting10 | Setting11 | Setting13 | Setting14 
1  | Off  | On  | not set | off 
2  | On  | not set | on  | not set 

給出SettingID的名單,也沒有必要進行分析,並自動找到它們。

不知道如何處理這個

回答

0

至於你說的settingid列表是固定的,你可以得到有條件的聚集所期望的結果。

select userid, 
max(case when settingid = '10' then 
            case when value = 0 then 'Off' 
             when value = 1 then 'On' 
            else 'not set' end 
    end) as setting10, 
--proceed similarly for other settings 
from yourtable 
group by userid; 
0

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 | 
0

這裏是你的問題

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX) 
DECLARE @ColumnName AS NVARCHAR(MAX) 
DECLARE @ColumnCaseName AS NVARCHAR(MAX) 

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
    + QUOTENAME(SettingID) 
FROM (SELECT DISTINCT SettingID FROM TableName) AS TableName 

SELECT @ColumnCaseName= ISNULL(@ColumnCaseName + ',','') 
    + 'case when '+QUOTENAME(SettingID)+' = 0 then ''Off'' when '+QUOTENAME(SettingID)+' = 1 then ''On'' else ''not set'' end ' 
+ QUOTENAME(SettingID) 
FROM (SELECT DISTINCT SettingID FROM TableName) AS TableName 

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
N'SELECT UserID, ' + @ColumnCaseName + ' 
FROM TableName 
PIVOT(Max(Value) 
     FOR SettingID IN (' + @ColumnName + ')) AS PVTTable' 
--Execute the Dynamic Pivot Query 
EXEC sp_executesql @DynamicPivotQuery 

這將爲你在表中添加任意數量的行工作的答案。

快樂編碼