在其他RDBMS上是否有任何等效的Postgresql EVERY聚合函数?

时间:2012-05-02 03:33:47

标签: database postgresql rdbms

每个聚合的文档:

every(expression):如果所有输入值都为true,则为true,否则为false

http://www.postgresql.org/docs/9.1/static/functions-aggregate.html


每个语义都等同于COUNT(conditionIsTrue)= COUNT(*)

select person_id, 

    every(visited_site = 'http://stackoverflow.com') as visited_same_site_forever,

    count(case when visited_site = 'http://stackoverflow.com' then '^_^' end) 
    = count(*) as visited_same_site_forever2

from z
group by person_id
order by person_id

输出:

 person_id | visited_same_site_forever | visited_same_site_forever2 
-----------+---------------------------+----------------------------
        88 | f                         | f
     55327 | t                         | t
    256196 | f                         | f

数据来源:

create table z(person_id int, visited_site varchar(100), datetime_visited timestamp);

insert into z values
(55327,'http://stackoverflow.com','Jan 1, 2010'),
(55327,'http://stackoverflow.com','Feb 14, 2012'),
(55327,'http://stackoverflow.com','May 1, 2012'),
(256196,'http://stackoverflow.com','February 1, 2012'),
(256196,'http://stackoverflow.com','February 2, 2012'),
(256196,'http://slashdot.org','May 2, 2012'),
(88,'http://theregister.co.uk','April 1, 2012'),
(88,'http://slashdot.org','April 2, 2012');

1 个答案:

答案 0 :(得分:5)

使用EVERY()CASE

模拟SUM()

事实上,this article describes how EVERY() can be emulated via CASE and SUM()。以下两个陈述是等效的:

SELECT EVERY(id < 10)
FROM book

SELECT CASE SUM(CASE WHEN id < 10 THEN 0 ELSE 1 END) 
         WHEN 0 THEN 1 
         ELSE 0 
       END
FROM book;

EVERY()窗函数也是如此:

SELECT 
  book.*, 
  EVERY(title LIKE '%a') OVER (PARTITION BY author_id)
FROM book

SELECT
  book.*,
  CASE SUM(CASE WHEN title LIKE '%a' THEN 0 ELSE 1 END)
       OVER(PARTITION BY author_id)
    WHEN 0 THEN 1 
    ELSE 0
  END
FROM book;

SQL标准

SQL:2008标准提到EVERY聚合函数:

10.9 <aggregate function>

[...]

<aggregate function> ::=
  COUNT <left paren> <asterisk> <right paren> [ <filter clause> ]
  | <general set function> [ <filter clause> ]
  | <binary set function> [ <filter clause> ]
  | <ordered set function> [ <filter clause> ]

<general set function> ::=
  <set function type> <left paren> [ <set quantifier> ]
  <value expression> <right paren>

<set function type> ::=
  <computational operation>

<computational operation> ::=
  AVG
  | MAX
  | MIN
  | SUM
  | EVERY
  | [...]

但是,“高级”SQL标准功能通常不是由数据库实现的。例如,Oracle 11g不支持它,SQL Server 2012也不支持它。

然而,使用HSQLDB,您可能会更幸运。 HSQLDB 2.x非常符合标准,也是MySQL knows the BIT_AND()聚合函数,它是EVERY()的非标准别名,也受Postgres支持。

请注意,某些数据库允许编写用户定义的聚合函数,因此您也可以自己实现EVERY()