[英]Get max/min value of the column independet from where clause
我有以下查詢並在 postgress 上運行它
select
p.id as p_id,
p.name as p_name,
p.tags,
p.creator,
p.value
p.creation_date,
cp.id as c_part_id,
fr.distance
count(*) OVER() AS total_item
from t_p p
left join t_c_part cp on p.id = cp.p_id
left join t_fl fr on p.id = fr.p_id
where p.name = 'test'
ORDER BY p.id ASC, p.name ASC
OFFSET 0 FETCH NEXT 25 ROWS only
這里缺少的是我還需要得到不受“where”子句影響的 max(p.value) 和 min(p.value) - 因此是從總(所有)值計算的。
我夢想我可以在一個查詢中完成並減少交易數量。 老實說,不確定是否可能!
我嘗試的是這樣的->
SELECT
(SELECT COUNT(*) from t_p) as count,
(SELECT json_agg(t.*) FROM (
SELECT * FROM t_p
where ***
) AS t) AS rows
但是這個看起來不是很好,因為它需要在后端進行額外的 JSON 操作。
我發現我可能會嘗試使用“with”語句來創建一個臨時視圖,因此 where 條件只評估一次,但沒有成功使其工作......
I am not totally certain if that's what you are asking, but to add minimum and maximum to the output, you could use a window function to the SELECT
list:
SELECT ...,
max(p.value) OVER (),
min(p.value) OVER ()
FROM ...
您可以將額外的列添加為(select min(value) from t_p)
形式的標量子查詢。 它們的值與主查詢無關,因此它們應該完全獨立。
您的原始查詢有一些小的語法問題(缺少逗號)。 我修復了這些,結果是:
select
p.id as p_id,
p.name as p_name,
p.tags,
p.creator,
p.value,
p.creation_date,
cp.p_id as c_part_id,
fr.distance,
count(*) OVER() AS total_item,
(select min(value) from t_p) as min_value,
(select max(value) from t_p) as max_value
from t_p p
left join t_c_part cp on p.id = cp.p_id
left join t_fl fr on p.id = fr.p_id
where p.name = 'test'
ORDER BY p.id ASC, p.name ASC
OFFSET 0 FETCH NEXT 25 ROWS only
請參閱DB Fiddle上的運行查詢(沒有任何數據)。
您可以加入計算 MIN 和 MAX 的子查詢。
...
from t_p p
left join t_c_part cp on p.id = cp.p_id
left join t_fl fr on p.id = fr.p_id
cross join (
select
min(value) as min_value
, max(value) as max_value
, avg(value) as avg_value
from t_p
) as v
...
然后在 select 中使用v.min_value
和v.max_value
。
甚至不必是 LATERAL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.