简体   繁体   English

避免在CASE表达式中调用两次COUNT(PostgreSQL)

[英]Avoid calling COUNT twice in CASE expression (PostgreSQL)

Inside a larger query, I have to COUNT a variable, then if it is larger than 1 , have the count as a string otherwise an empty string: 在更大的查询中,我必须COUNT一个变量,然后如果它大于1 ,则将计数作为字符串,否则为空字符串:

CASE COUNT(measurement.id) > 1 THEN to_char(COUNT(measurement.id),' 999') ELSE ''

I'm afraid this is slow because I use COUNT() twice. 我担心这很慢,因为我使用COUNT()两次。 Is there a better way? 有没有更好的办法?

This expression: 这个表达式:

CASE COUNT(measurement.id) > 1 THEN to_char(COUNT(measurement.id),' 999') ELSE ''

is not slow because COUNT() is called twice. 因为COUNT()被调用两次并不慢。 The hard work of aggregating the data is the part where the key values are brought together. 聚合数据的艰苦工作是将关键值集合在一起的部分。 The individual aggregation functions are generally not particularly expensive (there are exceptions such as COUNT(DISTINCT) ). 各个聚合函数通常不是特别昂贵(存在例如COUNT(DISTINCT) )。 So, even if it were being called multiple times, this would not be an issue. 所以,即使它被多次调用,这也不是问题。

You could change the query to something more cryptic like: 您可以将查询更改为更加神秘的内容:

coalesce(to_char(nullif(count(measurement.id), 0), '999')), '')

This takes a count of 0, converts it to NULL , which is then turned into an empty string (and I think it would only evaluate the argument once in Postgres, although SQL Server would evaluate it twice, in which case you use isnull() instead of coalesce() ). 这需要计数0,将其转换为NULL ,然后将其转换为空字符串(我认为它只会在Postgres中评估一次参数,尽管SQL Server会对它进行两次评估,在这种情况下你使用isnull()而不是coalesce() )。 I much prefer your version, if you feel the need to convert nice numbers into strings. 如果你觉得需要将好的数字转换成字符串,我更喜欢你的版本。

EDIT: 编辑:

COUNT() appears to be defined as "immutable" which is even stronger than "stable". COUNT()似乎被定义为“不可变”,甚至比“稳定”更强。 I'm not even sure if this is correct, but that is the case on SQL Fiddle . 我甚至不确定这是否正确,但SQL Fiddle就是这种情况。 In any case, it probably isn't called twice, but the expensive part is the GROUP BY anyway. 在任何情况下,它可能不会被调用两次,但昂贵的部分仍然是GROUP BY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM