在SQL中进行透视

时间:2015-02-12 05:09:11

标签: sql sql-server pivot

我想要一些帮助转动。我在SQL中有一个看起来像这样的数据集

ID-----------VisitDate----------Metric------Value  
1001---------2012-01-01---------Cajun-------40  
1001---------2012-01-02---------Cajun-------30  
1001---------2012-01-01---------Ham---------20  
1003---------2012-01-02---------Ham---------10  
1003---------2012-01-03---------Beef--------10 

如何根据ID和VisitDate Columns转动此数据集以便将其从长格式转换为宽格式,因此数据集看起来像这样:

ID-----------VisitDate----------Cajun------Ham--------Beef  
1001---------2012-01-01---------40---------20---------Null  
1001---------2012-01-02---------30---------Null-------Null  
1003---------2012-01-02---------Null-------10---------Null  
1003---------2012-01-03---------Null-------Null-------10 

3 个答案:

答案 0 :(得分:3)

如果你确定Metric的值只包含Cajun,Ham和Beef,那么这样就可以了:

SELECT
    Id,
    VisitDate,
    Cajun = MAX(CASE WHEN Metric = 'Cajun' THEN Value END),
    Ham = MAX(CASE WHEN Metric = 'Ham' THEN Value END),
    Beef = MAX(CASE WHEN Metric = 'Beef' THEN Value END)
FROM YourTable
GROUP BY ID, VisitDate
ORDER BY ID, VisitDate

另一方面,如果您不知道Metric的值,则可以使用动态交叉选项卡。供参考:http://www.sqlservercentral.com/articles/Crosstab/65048/

DECLARE @sql1 VARCHAR(4000) = ''
DECLARE @sql2 VARCHAR(4000) = ''
DECLARE @sql3 VARCHAR(4000) = ''

SELECT @sql1 = 
'SELECT
    ID
    ,VisitDate'
+ CHAR(10)

SELECT @sql2 = @sql2 +
'   ,MAX(CASE WHEN Metric = ''' + Metric + ''' THEN Value END) AS [' + Metric + ']' + CHAR(10)
FROM(
    SELECT DISTINCT Metric FROM YourTable
)t

SELECT @sql3 =
'FROM YourTable
GROUP BY ID, VisitDate
ORDER BY ID, VisitDate
'
PRINT(@sql1 + @sql2 + @sql3)
EXEC (@sql1 + @sql2 + @sql3)

<强> RESULT

ID          VisitDate  Beef        Cajun       Ham
----------- ---------- ----------- ----------- -----------
1001        2012-01-01 NULL        40          20
1001        2012-01-02 NULL        30          NULL
1003        2012-01-02 NULL        NULL        10
1003        2012-01-03 10          NULL        NULL

答案 1 :(得分:0)

这是sqlfiddle的链接: http://sqlfiddle.com/#!3/0445e/1

以下是使用PIVOT的样子:

SELECT
  ID,
  VisitDate,
  Cajun,
  Ham,
  Beef
FROM (  
  SELECT
    ID,
    VisitDate,
    Metric,
    Value
  FROM
    Bleh
) AS SourceTable PIVOT (
  MAX (Value) FOR Metric IN (Cajun, Ham, Beef)
) AS PivotTable

答案 2 :(得分:-1)

使用PIVOT获取结果。在Fiddler

中查看结果

参考。学习SQL SERVER – PIVOT and UNPIVOT Table Examples

SELECT id, 
       visitdate, 
       SUM([Cajun]) AS [Cajun], 
       SUM([Ham]) AS [Ham],
       SUM([beef]) AS [beef] 
FROM Test AS A
PIVOT(MIN(A.value) FOR A.metric IN ([Cajun],[Ham],[beef])) AS B
GROUP BY id, visitdate