我有一个表Machine_Mode_Duration:
我需要一个查询,以便显示如下:
建议表示赞赏!
答案 0 :(得分:3)
您需要GROUP BY
。
假设您有3种模式,并且在重复(Machine_id, INTERNAL_MODES)
元组的情况下,可以总结一下INTERNAL_MODE_DURATION
:
SELECT
Machine_Id,
SUM(CASE WHEN INTERNAL_MODES = 1 THEN INTERNAL_MODE_DURATION ELSE 0 END) AS Mode_1,
SUM(CASE WHEN INTERNAL_MODES = 2 THEN INTERNAL_MODE_DURATION ELSE 0 END) AS Mode_2,
SUM(CASE WHEN INTERNAL_MODES = 3 THEN INTERNAL_MODE_DURATION ELSE 0 END) AS Mode_3
FROM t
GROUP BY
Machine_Id;
答案 1 :(得分:1)
试试这个
select Machine_Id,
case when INTERNAL_MODES = 1 then INTERNAL_MODE_DURATION end as Mode_1,
case when INTERNAL_MODES = 2 then INTERNAL_MODE_DURATION end as Mode_2,
case when INTERNAL_MODES = 3 then INTERNAL_MODE_DURATION end as Mode_3
from Machine_Mode_Duration
group by Machine_Id
order by Machine_Id;
答案 2 :(得分:0)
您可以像这样使用PIVOT
SELECT Machine_ID,
[1] as Mode_1, [2] as Mode_2, [3] as Mode_3 FROM
(SELECT Machine_ID, Internal_Mode_Duration , InternalModes
FROM Machine_Mode_Duration) AS SourceTable
PIVOT
(
Sum(Internal_Mode_Duration)
FOR InternalModes IN ([1], [2], [3])
) AS PivotTable;
您也可以通过CASE
使用旧式方法,例如没有PIVOT
命令的时间;)