2017-10-28 57 views
-1

列表創建列我有以下數據:如何從價值

Table 1 
Row ID  Value  Cost 
1  1  Priority 1 10,000 
2  2  Priority 2 9,000 
3  3  Priority 3 8,000 
4  4  Priority 4 6,000 

Table 2 
Row Name Priority Cost 
1  Jon  1   10,000 
2  Bob  3   8,000 
3  Dan  4   7,000 
4  Steve 2   9,000 
5  Bill 3   8,000 
... 

我想表看起來像這樣:

Table 3 
Row Name  Priotity 1  Priority 2  Priority 3  Priority 4 
1 Jon  10,000 
2 Bob         8,000 
3 Dan             7,000 
4 Steve     9,000 
5 Bill         8,000 
... 

如何創建行從表1列,並填寫輸出,如表3所示。

我希望這不像它聽起來那麼基本,但我的SQL很糟糕!

+2

谷歌:「<數據庫名稱>動態轉動」。 –

回答

0

你可以試試這個動態數據透視表。

DECLARE @columns VARCHAR(8000) 


SELECT @columns = COALESCE(@columns + ',[' + cast(Value as varchar) + ']', 
'[' + cast(Value as varchar)+ ']') 
FROM Table1 
GROUP BY Value 

DECLARE @query VARCHAR(8000) 
SET @query = 'with Priorites as 
(select a.Name,b.Value,b.Cost from Table2 a left join Table1 b on a.Priority =b.id) 
SELECT * 
FROM Priorites 
PIVOT 
(
MAX(Cost) 
FOR [Value] 
IN (' + @columns + ') 
) 
AS p' 

EXECUTE(@query) 

在以下鏈接瞭解更多詳情http://www.tsqltutorials.com/pivot.php

0

Pivot總是在這種情況下是有用的,但是如果實際數據很簡單,因爲它是有問題(如只有4個獨特的Priority和/或僅1優先分配給特定用戶),那麼你可以用下面的查詢實現這個任務:

select t.row,t.name 
    (case when t.priority = 1 then t.cost 
     else ' ' 
    end 
) as Priority1, 
    (case when t.priority = 2 then t.cost 
     else ' ' 
    end 
) as Priority2, 
    (case when t.priority = 3 then t.cost 
     else ' ' 
    end 
) as Priority3, 
    (case when t.priority = 4 then t.cost 
     else ' ' 
    end 
) as Priority4 
From 
    (select Row,name,priority,cost 
    from Table2 
    group by name) t 
group by t.name;