首页 > 解决方案 > 为什么我必须在此列上使用聚合函数?

问题描述

我有一个看起来像这样的表:

+---------+---------------+------------+-------+
| country | company       | date       | sales |
+---------+---------------+------------+-------+
| US      | Amazon        | 2019-11-01 | 100   |  
| US      | Amazon        | 2019-12-01 | 120   |   
| US      | Apple         | 2019-11-01 | 100   | 
| US      | Apple         | 2019-12-01 | 150   | 
| DE      | Amazon        | 2019-11-01 | 200   | 
| DE      | Amazon        | 2019-12-01 | 300   |
+---------+---------------+------+-----+-------+

我想计算每个国家/地区每个公司的销售额月增长率。这是我的 SQL 代码:

select date_trunc('month', date),
        country,
        sum(sales),
        round(1.0 - sales::numeric/nullif(lag(sales::numeric, 1) over (order by date),0) *100,1) prev
from table 
group by date, country
order by date asc;

当我运行代码时,会出现此错误:

列“table.sales”必须出现在 GROUP BY 子句中或在聚合函数中使用

如何解决此错误?

标签: sqlpostgresql

解决方案


因为您需要滞后销售的总和,而不是列本身:

select date_trunc('month', date), country, sum(sales),
       round(1.0 - sum(sales)::numeric * 100.0 /
             nullif(lag(sum(sales)::numeric, 1) 
       over (order by date), 0), 1) prev
from table 
group by date, country
order by date asc;

推荐阅读