[英]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.