SQL - 选择分组行的一个实例

SQL - Select one instance of grouped rows(SQL - 选择分组行的一个实例)
本文介绍了SQL - 选择分组行的一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个对行进行分组的查询.产品 ID 相同但日期和数量不同的多行被分组,以便我可以计算数量、平均价格等的总和.

I have a query where rows are grouped. Multiple rows where the product ID are the same but where date and quantity differs, are grouped so I can calculate the sum of quantities, average prices, etc.

我现在需要添加上次销售的日期和相应的数量.日期加了MAX(date),怎么加对应的数量?

I now need to add the date when the last sale occurred and the corresponding quantity. I added the date with MAX(date), but how do I add the corresponding quantity?

我使用 MS SQL Server Management Studio.

I use MS SQL Server Management Studio.

示例查询:

SELECT id,
       SUM(quantity) as 'Total q',
       AVG(price) as 'Avg price',
       MAX(price) as 'Max price',
       MAX(date) as 'Last sale date'
FROM table
WHERE date > 2018
GROUP BY id

原始样本数据:

id     quantity    price     date
1      20          2.30      2018-6-2
1      10          2.40      2018-6-4
1      5           2.55      2018-6-10
2      15          12.50     2018-5-20
2      100         7.50      2018-6-1
2      50          10.00     2018-6-12

预期结果:

id    total q    avg price   max price   last sale    last q  last p
1     35         2.42        2.55        2018-6-10    5       2.55
2     165        10.00       12.50       2018-6-12    50      10.00

推荐答案

你可以使用窗口函数:

SELECT DISTINCT id,
       SUM(quantity) OVER(PARTITION BY id) as "Total q",
       AVG(price) OVER(PARTITION BY id) as "Avg price",
       MAX(price) OVER(PARTITION BY id) as "Max price",
       MAX(_date) OVER(PARTITION BY id) as "Last sale date",
       FIRST_VALUE(quantity) OVER(PARTITION BY id ORDER BY _date DESC) AS last_q,
       FIRST_VALUE(price) OVER(PARTITION BY id ORDER BY _date DESC) AS last_p
FROM tab
WHERE _date > '2018-01-01';

输出:

┌────┬─────────┬───────────┬───────────┬─────────────────────┬────────┬────────┐
│ id │ Total q │ Avg price │ Max price │   Last sale date    │ last_q │ last_p │
├────┼─────────┼───────────┼───────────┼─────────────────────┼────────┼────────┤
│  1 │      35 │  2.416666 │      2.55 │ 10/06/2018 00:00:00 │      5 │   2.55 │
│  2 │     165 │ 10.000000 │     12.50 │ 12/06/2018 00:00:00 │     50 │  10.00 │
└────┴─────────┴───────────┴───────────┴─────────────────────┴────────┴────────┘

DBFiddle 演示

这篇关于SQL - 选择分组行的一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)