請教SQL語法WITH AS, 資料庫使用的是PostgreSQL。
WITH
aggregate AS
(SELECT * FROM table1 where x=1),
inserts AS
(
**请问这里有办法用IF来判断条件吗?
**例如 IF EXISTS(select * from aggregate where x=1)
** THEN
** do something;
** END IF;
)
可以,使用function
配合case when
檢查是不是2的倍數
的Script
CREATE TABLE Table1
("x" int)
;
INSERT INTO Table1
("x")
VALUES
(1),
(2),
(3),
(4)
;
CREATE FUNCTION isMultiplesOf2(integer) RETURNS boolean
AS 'select MOD($1,2)=1 ;'
LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT;
WITH aggregate AS(
SELECT * FROM table1 where x in (1,4)
)
select
case when isMultiplesOf2(x) then 'true'
else 'false'
end isMultiplesOf2
from aggregate;
ismultiplesof2 |
---|
true |
false |