根据SQL Server标准将单列汇总到多个列

时间:2016-08-16 23:13:48

标签: sql sql-server sum pivot

现在我正在根据部分,工作,机器和类型进行分组来收集一些时间。

我希望将总计时间分成多个列而不是基于类型的多行。我怎么能这样做?

这是我的代码

SELECT
    m.[machineName]
    ,pr.[jobNumber]
    ,p.[partNumber]
    ,sc.[type]
    ,SUM(pl.[elapsedTime]) AS elapsedTime 
FROM wincc.dbo.productionLog pl
    INNER JOIN wincc.dbo.machines m        ON pl.[machineId]       = m.id
    INNER JOIN wincc.dbo.productionRuns pr ON pl.[productionRunId] = pr.id
    INNER JOIN wincc.dbo.parts p           ON pr.[partId]          = p.Id
    INNER JOIN wincc.dbo.statusCodes sc    ON pl.[statusCodeId]    = sc.id
GROUP BY
    m.[machineName]
    ,pr.[jobNumber]
    ,p.[partNumber]
    ,sc.[type]

产生:

enter image description here

但我想:

enter image description here

谢谢大家!

1 个答案:

答案 0 :(得分:3)

这是表pivoting的一种形式。这是使用conditional aggregation执行此操作的一种方法:

SELECT
    m.[machineName]
    ,pr.[jobNumber]
    ,p.[partNumber]
    ,SUM(CASE WHEN sc.Type = 'planned downtime' then pl.[elapsedTime] END) AS plannedDT
    ,SUM(CASE WHEN sc.Type = 'unplanned downtime' then pl.[elapsedTime] END) AS unplannedDT
    ,SUM(CASE WHEN sc.Type = 'production' then pl.[elapsedTime] END) AS production
    ,SUM(CASE WHEN sc.Type = 'rework' then pl.[elapsedTime] END) AS rework
FROM wincc.dbo.productionLog pl
    INNER JOIN wincc.dbo.machines m        ON pl.[machineId]       = m.id
    INNER JOIN wincc.dbo.productionRuns pr ON pl.[productionRunId] = pr.id
    INNER JOIN wincc.dbo.parts p           ON pr.[partId]          = p.Id
    INNER JOIN wincc.dbo.statusCodes sc    ON pl.[statusCodeId]    = sc.id
GROUP BY
    m.[machineName]
    ,pr.[jobNumber]
    ,p.[partNumber]