2017-10-28 54 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;