sql - 为什么我必须在此列上使用聚合函数?
问题描述
我有一个看起来像这样的表:
+---------+---------------+------------+-------+
| 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 子句中或在聚合函数中使用
如何解决此错误?
解决方案
因为您需要滞后销售的总和,而不是列本身:
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;
推荐阅读
- swift - 在路径中找不到 lintable 文件:'' Command PhaseScriptExecution failed with a nonzero exit code Swift 5
- thread-safety - 跨线程的句子阻塞?
- javascript - DISpatch 在 React Redux 中没有触发
- python - 如何获取用户输入,而不是将其转换为字符串数据类型?
- deep-learning - 比较两个分割图预测
- swift - 在快速发送消息时创建与 PPT 通信所需的 CFMessagePort 时出错
- javascript - 为什么我必须在 jQuery 中为元素和 .files 方法提供索引才能访问值?
- android - 我正在尝试使用 Firebase 播放视频,但它显示 DefaultHttpDataSourceFactory 已弃用
- python - 在指定数量的列中,找出每行中具有前 3 个最大值的列
- scala - Akka:Websocket 处理程序失败,无法订阅关闭的发布者