如何返回此查询的总和?

时间:2010-10-07 17:34:21

标签: sql oracle aggregate-functions

我有以下表格,我需要找出总和。

表A


ID Name
1 Jason
2 Peter 
3 Ravi

表B


ID ID_SEC
1 11
1 12
1 13
2 21
2 22
2 23
3 31
3 32
3 33

表C


ID_SEC  Value   Include_Ind
11  100         Y
12  200         Y
13  300         N
21  10          Y
22  20          N 
23  30          N
31  1000        N
32  2000        N
33  3000        N

输出


ID Name  Total  Include_Ind_count [only count when Y]
1 Jason  600     2
2 Peter  60      1
3 Ravi  6000     0

3 个答案:

答案 0 :(得分:3)

使用:

  SELECT a.id,
         a.name,
         SUM(c.value) AS total
    FROM TABLE_A a
    JOIN TABLE_B b ON b.id = a.id
    JOIN TABLE_C c ON c.id_sec = b.id_sec
GROUP BY a.id, a.name

答案 1 :(得分:3)

仅当标志设置为'Y'时计数INCLUDE_IND的技巧是使用CASE()来测试其值:

SQL> select a.id
  2          , a.name
  3         , sum ( c.val) as total
  4         , count( case when c.include_ind = 'Y' then 1
  5                       else null end ) as inc_ind_cnt
  6  from a
  7          join b on ( b.id = a.id )
  8          join c on ( c.id_sec = b.id_sec )
  9  group by a.name, a.id
 10  order by a.id
 11  /

        ID NAME            TOTAL INC_IND_CNT
---------- ---------- ---------- -----------
         1 Jason             600           2
         2 Peter              60           1
         3 Ravi             6000           0

SQL>

ORDER BY是保证排序顺序所必需的,因为Oracle改变了它在10g中用于GROUP BY操作的算法。

答案 2 :(得分:1)

您可以使用内部联接和SUM来获取结果 - 假设你tableC.Value是int字段。否则你需要施展它。

SELECT tabA.id, tabA.name, SUM(tabC.value)
FROM TABLE_A tabA
INNER JOIN TABLE_B tabB ON tabB.id = tabA.id
INNER JOIN TABLE_C tabc ON tabC.id_sec = tabB.id_sec
GROUP BY tabA.id, tabA.name