SQL:具有两列和平均值的分组的PostgresSQL-即使平均值为零,如何显示所有分组

时间:2019-04-28 01:02:26

标签: sql postgresql group-by

我有下表:

CREATE TABLE table1
    ("id" int, "day" varchar(8), "customer" varchar(1), "amount" int)
;


INSERT INTO Table1
    ("id", "day", "customer", "amount")
VALUES
    (1, 'Thursday', 'a', 10),
    (2, 'Thursday', 'a', 11),
    (3, 'Thursday', 'b', 12),
    (4, 'Friday', 'c', 13),
    (5, 'Friday', 'c', 14),
    (6, 'Saturday', 'c', 15),
    (7, 'Saturday', 'a', 16),
    (8, 'Saturday', 'c', 17),
    (9, 'Saturday', 'c', 18),
    (10, 'Saturday', 'a', 19)
;

我需要为每个每日客户组合提供平均金额(3x3 = 9行)。但是,当我在以下简单查询中使用此查询时,不会显示特定客户没有花钱的日子。我希望将它们包括在内并显示为零的平均值。

查询:

Select day, customer, avg(amount) 
FROM table1
GROUP BY day, customer 

结果:

+-----------+-----------+---------------------+
|   day     | customer  |         avg         |
+-----------+-----------+---------------------+
| Friday    | c         | 13.5000000000000000 |
| Saturday  | c         | 16.6666666666666667 |
| Thursday  | b         | 12.0000000000000000 |
| Thursday  | a         | 10.5000000000000000 |
| Saturday  | a         | 17.5000000000000000 |
+-----------+-----------+---------------------+

所需结果:

+----------+----------+------------------+
|   day    | customer |       avg        |
+----------+----------+------------------+
| Friday   | a        | 0                |
| Friday   | b        | 0                |
| Friday   | c        | 13.5             |
| Saturday | a        | 17.5             |
| Saturday | b        | 0                |
| Saturday | c        | 16.6666666666667 |
| Thursday | a        | 10.5             |
| Thursday | b        | 12               |
| Thursday | c        | 0                |
+----------+----------+------------------+

提琴:[https://www.db-fiddle.com/f/gT5FoFbvC951CHdFXBsfYH/0][1] 任何帮助深表感谢。

1 个答案:

答案 0 :(得分:1)

使用cross join生成行,使用left join引入值:

select d.day, c.customer, coalesce(avg(t.amount), 0)
from (select distinct day from table1) d cross join
     (select distinct customer from table1) c left join
     table1 t
     on t.day = d.day and t.customer = c.customer
group by d.day, c.customer;

如果您还有其他来源的客户或日子,则可以使用它们代替子查询。