我有一个查询
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;
我决定通过在WITH:
中添加新列来修改我的表count(*) FROM s154 GROUP BY section.
但是添加group by子句也要求组中的max和min。是否可以在WITH部分查询中计算部分?
答案 0 :(得分:4)
您只需添加count(*) over w
:
WITH s as (
SELECT SECTION, MAX(PRICE) over w as max_price,
MIN(PRICE) over w as min_price, AVG(PRICE) over w as avg_price,
TIME as t, price,
(case when MAX(PRICE) over w = price then TIME end) as maxt
(case when MIN(PRICE) over w = price then TIME end) as mint,
(COUNT(*) over w) as cnt
FROM s154 WINDOW w as (partition by section)
)
select DISTINCT SECTION, max_price, min_price, avg_price,
max(maxt) over (partition by section),
min(mint) over (partition by section),
cnt
from s;
我非常确定这个查询可以简化。我添加了一些内容,因此更容易理解:
as
,所以我可以知道名称的位置。我认为更简单的版本是:
SELECT SECTION, MAX(PRICE) as max_price,
MIN(PRICE) as min_price, AVG(PRICE) as avg_price,
(ARRAY_AGG(time ORDER BY price))[1] as time_at_min_price,
(ARRAY_AGG(time ORDER BY price DESC))[1] as time_at_max_price
FROM s154
GROUP BY section;
这似乎是表达逻辑的更好方法。