2014-05-08 180 views
-4

我有3個表電話簿,DynamicField,PhoneBook_DynamicField_RelT-SQL查詢與樞軸

電話簿:

|---ID----|---Name----| 
    1   Reza 
    2   Ali  

DynamicField:

|---ID----|--Caption--| 
    1   Job 
    2   Level 

PhoneBook_DynamicField_Rel:

|---ID----|--PhoneBookID--|--DynamicFieldID--|---Value---| 
    1   1     1    Emp 
    2   1     2    1 
    3   2     1    SomeJob  

我想對這個結果進行查詢:

|--PhoneBookID--|--Name--|--Job--|--Level--| 
     1   Reza  Emp  1 
     2   Ali SomeJob NULL 
+0

你嘗試過這麼遠嗎?不要在這裏寫一個問題,期待別人爲你做你的工作。 – Dan

+0

我不知道如何樞軸工作,我不希望其他人爲我做我的工作,只是我有問題,我認爲這個網站是爲它...你可以問,你不知道和迴應其他人回答什麼知道,並且相反,。我也想知道樞軸是如何工作的,這不是我的工作......這是我的問題 –

回答

1

也許是這樣的:

測試數據:

CREATE TABLE #PhoneBook(ID INT,Name VARCHAR(100)) 
INSERT INTO #PhoneBook VALUES(1,'Reza'),(2,'Ali') 

CREATE TABLE #DynamicField(ID INT,Caption VARCHAR(100)) 
INSERT INTO #DynamicField VALUES(1,'Job'),(2,'Level') 

CREATE TABLE #PhoneBook_DynamicField_Rel(ID INT,PhoneBookID INT, 
             DynamicFieldID INT,Value VARCHAR(100)) 
INSERT INTO #PhoneBook_DynamicField_Rel 
VALUES(1,1,1,'Emp'),(2,1,2,'1'),(3,2,1,'SomeJob') 

獲取colums

DECLARE @cols VARCHAR(MAX) 
SELECT @cols=STUFF 
(
    (
     SELECT 
      ',' +QUOTENAME(tbl.Caption) 
     FROM 
      #DynamicField AS tbl 
     FOR XML PATH('') 
    ) 
,1,1,'') 

那麼查詢就像這樣:

DECLARE @query NVARCHAR(4000)= 
N'SELECT 
    * 
FROM 
(
    SELECT 
     * 
    FROM 
    (
     SELECT 
      PhoneBook.ID, 
      PhoneBook.Name, 
      field.Caption, 
      rel.Value 
     FROM 
      #PhoneBook AS PhoneBook 
      JOIN #PhoneBook_DynamicField_Rel AS rel 
       ON PhoneBook.ID = rel.PhoneBookID 
      JOIN #DynamicField AS field 
       ON rel.DynamicFieldID=field.ID 
    ) AS SourceTable 
) AS p 
PIVOT 
(
    MAX(Value) FOR Caption IN('[email protected]+') 
) AS pvt' 
EXECUTE(@query) 

然後在我的情況下,我會刪除臨時表:

DROP TABLE #PhoneBook 
DROP TABLE #DynamicField 
DROP TABLE #PhoneBook_DynamicField_Rel 
1

你需要的是動態的支點:

declare @collist nvarchar(max) 
SET @collist = stuff((select distinct ',' + QUOTENAME(caption) 
      FROM DynamicField 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 

declare @q nvarchar(max) 
set @q = ' 
select PhoneBookID, Name, ' + @collist + ' 
from (
    select PhoneBookID, Name, Caption, Value 
     from (
     select PhoneBookID, Name, Caption, Value 
     from PhoneBook pb 
     inner join PhoneBook_DynamicField_Rel pbdf on pb.ID = pbdf.PhoneBookID 
     inner join DynamicField df on df.ID = pbdf.DynamicFieldID 
    ) as x 
) as source 
pivot (
    max(Value) 
    for caption in (' + @collist + ') 
) as pvt 
' 

exec (@q)