2015-10-21 74 views
-1

我有從3和不同的表3列如下顯示列值:如何在SQL一個單獨的列

Job  Region  Status 
1   Asia  Started 
1   Europe  In Progress 
1   Americas Not Started 
2   ASIA  Completed 
2   Europe  Not Started 
2   Americas Not Started 

我希望它被顯示在下面的格式:

Job  ASIA  Europe  Americas 
1  Started In Progress Not Started 
2  Completed Not Started Not Started 

有人可以幫我寫這個sql代碼嗎?

回答

2

一個簡單的條件聚集會做的伎倆:如果您有未知Region小號

SELECT 
    Job, 
    Asia  = MAX(CASE WHEN Region = 'Asia' THEN Status END), 
    Europe = MAX(CASE WHEN Region = 'Europe' THEN Status END), 
    Americas = MAX(CASE WHEN Region = 'Americas' THEN Status END) 
FROM tbl 
GROUP BY Job 

,您可以使用動態交叉做到這一點:

DECLARE @sql NVARCHAR(MAX) = '' 

SELECT @sql = 
'SELECT 
    Job' + CHAR(10) 

SELECT @sql = @sql + 
' , MAX(CASE WHEN Region = '''+ Region +''' THEN Status END) AS ' + QUOTENAME(Region) + CHAR(10) 
FROM(
    SELECT DISTINCT Region FROM tbl 
) t 

SELECT @sql = @sql + 
'FROM tbl 
GROUP BY Job' 

PRINT(@sql) 
EXEC (@sql) 

SQL Fiddle

相關問題