如何在SQL中组合类似的列?

时间:2016-02-11 19:35:44

标签: sql oracle

每个门我有3种可能的延迟类别。我试图在每个类别的特定门口找到Tot_Delay_Min,因此我需要找到一种方法将这些延迟类别组合成一个列,并将该类别的总分钟组合到另一个列中。 DLY1MIN,DLY2MIN和DLY3MIN对应DLY1CAT,DLY2CAT和DLY3CAT。

这是我对一个门的样本:

Gate     DLY1CAT     DLY1MIN      DLY2CAT      DLY2MIN     DLY3CAT     DLY3MIN
====     =======     =======      =======      =======     =======     =======
SDF      Weather     50           Fuel         3
SDF      Late Jet    10           Weather      9
SDF      Deice       9
SDF      Late Jet    7            Fuel         11
SDF      Computer    20           Weather      13
SDF      Load Issue  8            Deice        5           Fuel        3
SDF      Damage      20           Deice        7         

这是我想要的样本:

Gate     DLYCAT     DLYMIN
====     =======    =======
SDF      Weather    72
SDF      Deice      21
SDF      Computer   20
SDF      Damage     20
SDF      Fuel       17
SDF      Late Jet   17
SDF      Load Issue 8

有关如何解决此问题的任何提示?

3 个答案:

答案 0 :(得分:2)

这是未经测试的,我确​​信有更好的方法可以做到这一点,但这应该有效:

sudo service mongod start

您在这里做的是为每个类别分别进行三次查询 - 然后通过UNION ALL进行组合。然后,您可以从组合结果集和按门分组以及新创建的“类别”列中进行选择。

编辑:

删除了三个内部查询中的分组,因为它们是不必要的。

第二次编辑:

将括号更改为刻度,因为它是Oracle - 谢谢,a_horse_with_no_name

第三次编辑:

仅在需要时包含引号。最后添加分号。删除了Oracle兼容性的表别名。

答案 1 :(得分:0)

试试这个并告诉我它是否有效。

    Select Gate, DLYCAT AS DLYCAT, SUM(DLYMIN) AS DLYMIN
FROM
(Select Gate, DLY1CAT AS DLYCAT, SUM(DLY1MIN) AS DLYMIN FROM [ExperimentalDatabase].[dbo].[Table_1] GROUP BY GATE, DLY1CAT
UNION ALL
Select Gate, DLY2CAT AS DLYCAT, SUM(DLY2MIN) AS DLYMIN FROM [ExperimentalDatabase].[dbo].[Table_1] GROUP BY GATE, DLY2CAT
UNION ALL
Select Gate, DLY3CAT AS DLYCAT, SUM(DLY3MIN) AS DLYMIN FROM [ExperimentalDatabase].[dbo].[Table_1] GROUP BY GATE, DLY3CAT) AS TEMP
WHERE DLYCAT IS NOT NULL AND DLYMIN IS NOT NULL
GROUP BY GATE, DLYCAT

答案 2 :(得分:0)

我会尝试只使用一个聚合和union all(或取消忽略):

select gate, dlycat, sum(DLYMIN) as DLYMIN
from ((select Gate, DLY1CAT AS DLYCAT, DLY1MIN AS DLYMIN
       from [ExperimentalDatabase].[dbo].[Table_1] 
      ) union all
      (select Gate, DLY2CAT AS DLYCAT, DLY2MIN AS DLYMIN
       from [ExperimentalDatabase].[dbo].[Table_1] 
      ) union all
      (select Gate, DLY3CAT AS DLYCAT, DLY1MIN AS DLYMIN
       from [ExperimentalDatabase].[dbo].[Table_1] 
      )
     ) g
where dlycat is not null
group by gate, dlycat;