[英]SQL Outer Join on multiple summed columns in same table
我正在使用一个SQL库(编程库,符合ANSI SQL的ABS数据库,(http://www.componentace.com/help/absdb_manual/absdbmanual_content.htm)。它支持各种联接,CASE等。 。
我有一个表(appt),它是约会表。
ApptKey - Integer - Primary Key
SA_ID - Integer (a person’s ID, think employee number),
Layer - Integer – only 4 different values, 1, 2, 3 or 4 (think Appt Category)
Number_Of_Minutes - Integer – the length of the appointment
请注意,某些SA_ID / Layer组合可能为空(即该组合没有行)。 其他SA_ID / Layer组合可能具有多个行(我不在此显示其他列,因为它们在此处不相关)。 我需要一个报告来显示每一层每一人的时间总和(SA_ID),在一行中…即每个SA_ID都有自己的行,显示Layer = 1的总和,layer = 2的总和, Layer = 3的总和,layer = 4的总和。
示例数据…
SA_ID LAYER Number_of_Minutes
1 1 10
1 1 30
2 1 10
3 2 10
1 4 10
我需要一个给出此结果的查询。
SA_ID LAYER_1 LAYER_2 LAYER_3 LAYER_4
1 40 0 0 10
2 10 0 0 0
3 0 10 0 0
我需要这种格式,因为此查询提供了一个图表/图形组件…
我想我需要使用一个正确的联接多个相关的子查询,但我只是无法使其正常工作。 这是正确的方法吗? 我下面的内容可以运行,但是可以直接连接。 我可以(或如何)重写它以使用正确的外部联接吗? 正确的外部联接是最好的方法吗?
select g.sa_id, l1.totalsum, l2.totalsum, l3.totalsum, l4.totalsum
from (select sa_id, layer, sum(number_of_minutes) totalsum from appt where layer = 1 group by sa_id, layer) l1,
(select sa_id, layer, sum(number_of_minutes) totalsum from appt where layer = 2 group by sa_id, layer) l2,
(select sa_id, layer, sum(number_of_minutes) totalsum from appt where layer = 3 group by sa_id, layer) l3,
(select sa_id, layer, sum(number_of_minutes) totalsum from appt where layer = 4 group by sa_id, layer) l4,
(select distinct sa_id "sa_id" from appt) g
where
(l1.sa_id = g.sa_id)
and (l2.sa_id = g.sa_id)
and (l3.sa_id = g.sa_id)
and (l4.sa_id = g.sa_id)
SELECT SA_ID,
SUM(CASE WHEN LAYER = 1 THEN Number_of_Minutes ELSE 0 END) AS LAYER_1,
SUM(CASE WHEN LAYER = 2 THEN Number_of_Minutes ELSE 0 END) AS LAYER_2,
SUM(CASE WHEN LAYER = 3 THEN Number_of_Minutes ELSE 0 END) AS LAYER_3,
SUM(CASE WHEN LAYER = 4 THEN Number_of_Minutes ELSE 0 END) AS LAYER_4
FROM Appt
GROUP BY SA_ID
编辑:因为它支持CASE
表达式。
SELECT
t.sa_id,
Layer1=(SELECT SUM(Number_of_Minutes) FROM appt WHERE sa_id = t.sa_id AND Layer = 1),
Layer2=(SELECT SUM(Number_of_Minutes) FROM appt WHERE sa_id = t.sa_id AND Layer = 2),
Layer3=(SELECT SUM(Number_of_Minutes) FROM appt WHERE sa_id = t.sa_id AND Layer = 3),
Layer4=(SELECT SUM(Number_of_Minutes) FROM appt WHERE sa_id = t.sa_id AND Layer = 4)
FROM
(
SELECT DISTINCT
sa_id
FROM appt
) t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.