gpt4 book ai didi

sql - 如何获取最小和最大请求​​的时间?

转载 作者:行者123 更新时间:2023-11-29 14:17:02 25 4
gpt4 key购买 nike

我有一张包含产品部分的表格。

__________________________________
| SECTION| PRICE | TIME |
|--------------------------------|
| sec1 | 10 | 06-12-17 12:00|
| sec2 | 20 | 06-12-17 12:01|
| sec1 | 20 | 06-12-17 12:02|
| sec1 | 30 | 06-12-17 12:03|
| sec2 | 30 | 06-12-17 12:04|
----------------------------------

我需要为每个部分设置最小值、最大值和平均值。我做到了。

SELECT MAX(PRICE), MIN(PRICE), AVG(PRICE) FROM table1 GROUP BY SECTION;

我还需要一个最低价和最高价的销售时间。如果最大的销售发生在不同的时间,我需要它们中的任何一个。如何在一张表中获取?

___________________________________________________________
| SECTION| MIN | MAX | AVG | TIME OF MAX | TIME OF MIN |
|----------------------------------------------------------|
| sec1 | 10 | 30 | 20 | 06-12-17 12:03 |06-12-17 12:00|
| sec2 | 20 | 30 | 25 | 06-12-17 12:04 |06-12-17 12:01|
-----------------------------------------------------------

最佳答案

在没有三重连接的情况下使用窗口函数:

t=# WITH a as (
SELECT
SECTION
, MAX(PRICE) over w
, MIN(PRICE) over w
, AVG(PRICE) over w
, TIME t, price
, case when MAX(PRICE) over w = price then TIME end maxt
, case when MIN(PRICE) over w = price then TIME end mint
FROM s154
WINDOW w as (partition by section)
)
select DISTINCT
SECTION
, MAX
, MIN
, AVG
, max(maxt) over (partition by section)
, min(mint) over (partition by section)
from a
;
section | max | min | avg | max | min
----------+-----+-----+---------------------+---------------------+---------------------
sec1 | 30 | 10 | 20.0000000000000000 | 2017-06-12 12:03:00 | 2017-06-12 12:00:00
sec2 | 30 | 20 | 25.0000000000000000 | 2017-06-12 12:04:00 | 2017-06-12 12:01:00
(2 rows)

另外正如 Abelisto 指出的那样,on larger data sets ,在聚合之前过滤结果可以显着降低成本。所以加入

where maxt is not null or mint is not null

推荐到最后。

关于sql - 如何获取最小和最大请求​​的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44492924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com