SQL Outer在同一个表中连接多个求和列

时间:2012-01-12 13:07:21

标签: sql join self outer-join

我正在使用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)

2 个答案:

答案 0 :(得分:1)

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个表达式。

答案 1 :(得分:0)

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