使用嵌套聚合函数按行分组的总和

时间:2015-11-04 23:07:06

标签: sql postgresql case aggregate-functions aggregate

我有两张桌子

产品:

Res    ID    Code    Type
1      A      A-01    High
2      A      A-02    Medium
3      B      B-02    Medium
4      B      B-03    High
5      C      C-01    Low
6      C      C-03    Low

预留:

Res    ID    High    Medium    Low
1      A     3       0         0
2      A     0       5         0
3      B     0       4         0
4      B     3       0         0
5      C     0       0         4
6      C     0       0         3

我正在尝试获取按ID

分组的所有值的总和

我可以按类型使用

按类型获得总和
select 
product.res,
product.type,
count(product.type),
case
    when product.type='high' then reservation.high
    when product.type='medium' then reservation.medium
    when product.type='low' then reservation.low
    else 0
end,

case
    when product.type='high' then reservation.high* count(product.type)
    when product.type='medium' then reservation.medium* count(product.type)
    when product.type='low' then reservation.low* count(product.type)
    else 0
end

from pallets

left join reservation
on product.res=reservation.res

group by 
product.id,
product.type,
product.res,
reservation.high,
reservation.medium,
reservation.low

by product.id, product.res

我知道需要获取按ID分组的所有值的总和。 所以我正在寻找的是

ID    Total
A     8
B     7
C     7

当试图解决这个问题时,继续遇到嵌套聚合错误。 我正在使用Postrgres 9.5

1 个答案:

答案 0 :(得分:0)

我希望它就这么简单。我们以保留表为例:

create table reservation (res int, id char(1), high int, medium int, low int);
insert into reservation values
(1,'A',3,0,0),
(2,'A',0,5,0),
(3,'B',0,4,0),
(4,'B',3,0,0),
(5,'C',0,0,4),
(6,'C',0,0,3);

select id, sum(high + medium + low)
from reservation
group by id
order by id;

结果:

| id | sum |
|----|-----|
|  A |   8 |
|  B |   7 |
|  C |   7 |

示例:http://sqlfiddle.com/#!15/cb874/2

编辑:

假设以下数据结构:

预留:

+------+------+------+--------+------+
| res  | id   | high | medium | low  |
+------+------+------+--------+------+
|    1 | A    |    3 |      0 |    0 |
|    2 | A    |    0 |      5 |    0 |
|    3 | B    |    0 |      4 |    0 |
|    4 | B    |    3 |      0 |    0 |
|    5 | C    |    0 |      0 |    4 |
|    6 | C    |    0 |      0 |    3 |
+------+------+------+--------+------+

产品:

+------+------+------+--------+
| res  | id   | code | type   |
+------+------+------+--------+
|    1 | A    | A-01 | High   |
|    1 | A    | A-01 | High   |
|    2 | A    | A-02 | Medium |
|    2 | A    | A-03 | Medium |
|    3 | B    | B-02 | Medium |
|    4 | B    | B-03 | High   |
|    5 | C    | C-01 | Low    |
|    6 | C    | C-03 | Low    |
+------+------+------+--------+

SQL:

select
  p.id,
  sum(case 
      when p.type = 'High' then r.high
      when p.type = 'Medium' then r.medium
      when p.type = 'Low' then r.low
      end) tot
from product p
inner join reservation r on p.res = r.res
group by p.id

结果:

+------+------+
| id   | tot  |
+------+------+
| A    |   16 |
| B    |    7 |
| C    |    7 |
+------+------+