Emulare EVERY() con CASE e SUM()
Infatti, questo articolo descrive come EVERY() può essere emulato tramite CASE e SUM()
. Le due affermazioni seguenti sono equivalenti:
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;
Lo stesso vale per EVERY() funzione finestra:
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;
Standard SQL
Il SQL:2008 lo standard menziona EVERY funzione aggregata:
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
| [...]
Ma le funzionalità standard di SQL "avanzate" non sono spesso implementate dai database. Oracle 11g ad esempio, non lo supporta, né SQL Server 2012 .
Con HSQLDB
, tuttavia, potresti essere più fortunato. HSQLDB 2.x è molto conforme agli standard, inoltre MySQL conosce il BIT_AND()
funzione di aggregazione, che è un alias non standard per EVERY() , supportato anche da Postgres.
Nota, alcuni database consentono di scrivere funzioni aggregate definite dall'utente, quindi puoi anche implementare EVERY() te stesso.