ã¯ããã«
ã2009å¹´7æã«æ£å¼ãªãªã¼ã¹ãããPostgreSQL 8.4ã§ãåæé¢æ°ï¼windowé¢æ°ï¼ããµãã¼ãããã¾ãããæ¬é£è¼ã§ã¯ãåæé¢æ°ã®è¡æã·ãªã¼ãºããPostgreSQLç¨ã«ã¢ã¬ã³ã¸ããå 容ã¨ãOracleãDB2ã®åæé¢æ°ãPostgreSQL 8.4ã§ä»£ç¨ããæ¹æ³ãæ±ãã¾ãã
ãæ¬ç¨¿ã§ã¯ããåæé¢æ°ã®è¡æ1 ï¼åç·¨ï¼ãããPostgreSQL8.4ç¨ã«ãªãã¥ã¼ã¢ã«ããå 容ãæ±ãã¾ãã
対象èªè
- PostgreSQLã§windowé¢æ°ã使ã£ã¦ã¿ããæ¹
- åæé¢æ°ã®ç解ãæ·±ãããæ¹
ããHAVINGå¥ã®åãã«è¨è¼ããã¦ããSQLãwindowé¢æ°ã使ã£ã¦è¨è¿°ãã¦ããã¾ãã®ã§ããHAVINGå¥ã®åããèªã¾ãã¦ããã®æ¹ãç解ããããã¨æãã¾ãã
å¿ è¦ãªç°å¢
ãæ¬ç¨¿ã§æ±ãSQLã¯ãPostgreSQL 8.4 beta2ã§åä½ç¢ºèªãã¾ããããã®ä»ã次ã®ç°å¢ã§ãå¿ç¨ãå¯è½ã§ãã
- Oracle
- DB2
- SQL Server
1. æ¯æããæ¢ã
ãã¾ãã¯æ¯æããæ¢ãSQLã«ã¤ãã¦ã§ãããHAVINGå¥ã®åãã§ã¯ãæ¯æãã®æå°å¤ãæ¢ã2ã¤ã®SQLãæ示ããã¦ãã¾ãã
SELECT 'æ¯æããã' AS gap FROM SeqTbl HAVING COUNT(*) <> MAX(seq);
SELECT MIN(seq + 1) AS gap FROM SeqTbl WHERE (seq+ 1) NOT IN ( SELECT seq FROM SeqTbl);
ãããããwindow
é¢æ°ã§æ¸ãæãã¦ã¿ã¾ãã æåã®SQLã§æ¯æãã®æç¡ã調ã¹ã次ã®SQLã§æ¯æãã®æå°å¤ãæ¢ãã¦ã¾ããã ããã2ã¤ãã¾ã¨ãã¦ã以ä¸ã®ä»æ§ãæºããSQLãä½ãã¾ãã
case1 case2 case3 case4 case5 seq seq seq seq seq ----- ----- ----- ----- ---------- 1 1 2 1 ãã¼ã¿ãªã 2 2 3 2 3 3 4 3 5 4 4 6 6 5 case1ã§ã¯ãæ¯æãã®æå°å¤ã¨ãã¦4ãè¿ãã case2ã§ã¯ãæ¯æãã®æå°å¤ã¨ãã¦5ãè¿ãã case3ã§ã¯ãæ¯æãã®æå°å¤ã¨ãã¦1ãè¿ãã case4ã§ã¯ãæ¯æãã®æå°å¤ã¨ãã¦6ãè¿ãã case5ã§ã¯ãæ¯æãã®æå°å¤ã¨ãã¦1ãè¿ãã
ãçãã¯ãä¸è¨ã¨ãªãã¾ãã
select coalesce(max(seq), 0) + 1 as gap from (select seq, Row_Number() over(order by seq) as Rn from SeqTbl) a where seq = Rn;
ãSQLã®å¦çã¤ã¡ã¼ã¸ã¨èãæ¹ã¯ä»¥ä¸ã®éãã§ãããªããseqã®é ä½ãæã¤Rnåãä»ä¸ãã¦èãã¾ãã
case1 case2 case3 case4 case5 seq Rn seq Rn seq Rn seq Rn seq Rn --- -- --- -- --- -- --- -- --- ----- 1 1 1 1 2 1 1 1 ãã¼ã¿ãªã 2 2 2 2 3 2 2 2 3 3 3 3 4 3 3 3 5 4 4 4 4 4 6 5 6 5 5 5
ãcase1ã¨case2ã«æ³¨ç®ããã¨ã1ããï¼æ¯æãã®æå°å¤ - 1ï¼ã¾ã§ãseqã¨Rnãçãããã¨ãåããã¾ããcase4ã«æ³¨ç®ããã¨ãå
¨ã¬ã³ã¼ãã®seqã¨Rnãçãããã¨ãåããã¾ããcase1ã¨case2ã¨case4ã§ã¯ãseqã¨Rnãçãããªãã§æ大ã®seqã«1足ããå¤ããæ¯æãã®æå°å¤ã«ãªã£ã¦ãããã¨ãåããã¾ããcase3ã¨case5ã§ã¯ãseqã¨Rnãçãããªãã§æ大ã®seqããnullã¨ãªãã®ã§ãcoalesce
é¢æ°ã§å¯¾å¿ãã¦ã¾ãã
ãä¸è¨ã®ããã«ãç´°ããå ´ååããè¡ã£ã¦æ¤è¨¼ããã®ãä¸ã¤ã®æ¹æ³ã§ããããåæé¢æ°ã®è¡æ5 ï¼ç·éç·¨ï¼ãã§æ±ã£ãããã«ãæ 人ç®ã®æè¦ã使ã£ã¦ãããã§ãããã