在SQL层次结构中分组

时间:2015-04-30 07:24:18

标签: sql oracle

我还是SQL新手,我的问题有点长。好的,这是......我的任务是计算位于特定位置的机器的总停机时间。每台机器都有父母,子女和孙子女。例如:

Location:A1
Machine no:A1-100, A1-100-01, A1-100-01-001, A1-200, A1-200-01
(A1-100-01, A1-100-01-001 belongs to A1-100) and (A1-200-01 belongs to A1-200)

这是我的SQL查询: select machine_no, downtime from table_name where location='A1'

输出结果为:

machine_no       downtime
A1-100-01           2
A1-100              1.5
A1-200              3
A1-100-01-001       0.5
A2-200-01           1.5

我的问题是如何将子孙分组给父母并显示该群体的总停机时间?如果问题令人困惑,我很抱歉,但基本上我希望输出是这样的:

machine_no         total_downtime
A1-100                   4        (total of A1-100,A1-100-01,A1-100-01-001)
A1-200                   4.5      (total of A1-200,A1-200-01)

谢谢。

2 个答案:

答案 0 :(得分:0)

您可以将group bysum一起使用,如:

select machine_no, sum(downtime) from table_name where location like 'A1-100%' group by machine_no;

答案 1 :(得分:0)

尝试以下查询:

SELECT machine_no, SUM(downtime) as total_downtime
FROM ( 
  SELECT 
         SUBSTR(machine_no, 1,
             CASE WHEN INSTR(machine_no, '-', 1, 2) = 0 THEN LENGTH(machine_no) ELSE INSTR(machine_no, '-', 1, 2)-1 END
             ) as machine_no, -- this will get the part of machine_no before the second '-' char
         downtime 
  FROM MyTable 
  WHERE location='A1'
) InnerQuery
GROUP BY machine_no

输出:

 machine_no    total_downtime
 A1-100        4    
 A1-200        4.5

您实际上并不需要内部查询,但它比SUBSTR(....)表达式分组更具可读性。

Play with it yourself on sql fiddle

相关问题