sql - sql group by 没有 sum 函数
问题描述
我有这样的表Products
:
date | product | amount | gross
1-) 10/03/2020 | TV | 300 | 500
2-) 10/03/2020 | Table | 200 | 400
3-) 10/03/2020 | Phone | 100 | 200
4-) 10/02/2020 | Table | 40 | 215
5-) 10/02/2020 | Phone | 35 | 100
6-) 10/01/2020 | Tv | 145 | 420
7-) 10/12/2019 | Table | 400 | 800
8-) 10/12/2019 | Tv | 200 | 450
我想要做的是根据日期对表格进行分组,并在另一列中写入产品和金额
结果表应该是这样的:
date |product1|amount1|gross1|product2|amount2| gross2|product3|amount3 |gross3
1-) 10/03/2020 | TV | 300 | 500 |Table |200 |400 |Phone |100 |200
2-) 10/02/2020 | Table | 40 | 215 |Phone |35 |100 |null |null |null
3-) 10/01/2020 | Tv | 145 | 420 |null |null |null |null |null |null
4-) 10/12/2019 | Table | 400 | 800 |Tv |200 |450 |null |null |null
我尝试使用 group by 但它不起作用,因为我不需要 sum 函数来计算金额。你知道我能做什么吗?
select
date, product1, amount1, gross1,
product2, amount2, gross2,
product3, amount3, gross3
from
Products
group by
date
解决方案
For a fixed count of products per day, you can use conditional aggregation - but you need a column that defines the ordering of rows having the same date, I assumed id
:
select date,
max(case when rn = 1 then product end) as product1,
max(case when rn = 1 then amount end) as amount1,
max(case when rn = 1 then gross end) as gross1,
max(case when rn = 2 then product end) as product2,
max(case when rn = 2 then amount end) as amount2,
max(case when rn = 2 then gross end) as gross2,
max(case when rn = 3 then product end) as product3,
max(case when rn = 3 then amount end) as amount3,
max(case when rn = 3 then gross end) as gross3
from (
select t.*,
row_number() over(partition by date order by id) as rn
from mytable t
) t
group by date
order by date desc
推荐阅读
- gitpod - 什么是 gitpod:它实际上做了什么?
- node.js - Microsoft Teams 机器人查找消息发件人 ID
- oracle - 在 Citrix 中运行的 Oracle 应用程序的在家工作常见问题解答
- python-3.x - 在 python 中导入图像时,图像类型会发生什么?
- python - 如何在python中根据用户请求发送电子邮件?
- nativescript - 调整stacklayout滚动视图nativescript的大小
- javascript - 我收到有关 gapi 的参考错误
- java - 使用 Java 将文件从一个 AWS S3 存储桶复制到另一个 S3 存储桶
- javascript - VS Code Node.js macOS 调试不起作用 - 我什至不知道如何说明问题
- python - .bin 文件的 Python Big-Endian 转换