iT邦幫忙

0

SQL 語法請教 WITH AS

Ks 2018-10-05 16:19:393992 瀏覽
  • 分享至 

  • xImage

請教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;
    )
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
暐翰
iT邦大師 1 級 ‧ 2018-10-05 16:47:44
最佳解答

可以,使用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

線上測試連結DB Fiddle - SQL Database Playground

Ks iT邦新手 3 級 ‧ 2018-10-05 18:23:52 檢舉

了解,感谢大大回答/images/emoticon/emoticon02.gif

暐翰 iT邦大師 1 級 ‧ 2018-10-05 18:32:22 檢舉

/images/emoticon/emoticon12.gif

Ks iT邦新手 3 級 ‧ 2018-10-08 11:27:40 檢舉

.

我要發表回答

立即登入回答