ã¯ããã«
ãSQLã§ã¯ãåãè¡å
ã®åå士ãæ¯è¼ãããã¨ã¯ç°¡åã«ã§ãã¾ããæ®éã«WHERE
å¥ã«ãcol_1 = col_2ãã®ããã«æ¸ãã°ããã ãã§ããããä¸æ¹ãç°ãªãè¡ã®éã§åå士ãæ¯è¼ãããã¨ã¯ãããã»ã©ç°¡åã§ã¯ããã¾ãããã§ããããã¯ãSQLã§è¡éæ¯è¼ãã§ããªãã¨ãããã¨ã§ã¯ããã¾ãããæç¶ãåè¨èªã¨ã¯ããªãç°ãªãçºæ³ã«åºã¥ãã¦ãã¾ãããSQLã§ãããããå¦çãè¨è¿°ãããã¨ãå¯è½ã§ãã
ãSQLã§è¡éæ¯è¼ãããéã«å¨åãçºæ®ããã®ãç¸é¢ãµãã¯ã¨ãªãç¹ã«èªå·±çµåã¨çµã¿åããããèªå·±ç¸é¢ãµãã¯ã¨ãªãã§ããæ¬ç¨¿ã§ã¯ããã®æè¡ã使ã£ãè¡éæ¯è¼ã®å¿ç¨æ¹æ³ããå ·ä½ä¾ãéãã¦è§£èª¬ãã¾ãã
稼åç°å¢
- Oracle
- SQL Server
- DB2
- PostgreSQL
- MySQLï¼ãã¼ã¸ã§ã³4.1以ä¸ï¼
対象èªè
ãç¸é¢ãµãã¯ã¨ãªã®åºæ¬çãªä½¿ãæ¹ãç¥ã£ã¦ããæ¹ãCASEå¼ãèªå·±çµåãã¹ã«ã©ã»ãµãã¯ã¨ãªã«ã¤ãã¦ã®ç¥èãããã¨æã¾ããã§ããã¨ããããèªå·±çµåã¨è¦ªåæ§ãé«ãæè¡ãªã®ã§ãæªèªã®æ¹ã¯ãèªå·±çµåã®ä½¿ãæ¹ããå ã«èªãã¨ç解ãå¢ãã§ãããã
æé·ã»å¾éã»ç¾ç¶ç¶æ
ãè¡éæ¯è¼ãå¿ è¦ã«ãªã代表çãªæ¥åè¦ä»¶ã¨ãã¦ãçµæçãªãã¼ã¿ãè¨é²ãããã¼ãã«ã使ã£ã¦ãæç³»ååæãè¡ãã±ã¼ã¹ãããã¾ããä¾ãã°ãããä¼ç¤¾ã®å¹´åãè¨é²ãã次ã®ãããªãã¼ãã«ãèãã¾ãã
年度ï¼yearï¼ | å¹´åï¼ååï¼ï¼saleï¼ |
1990 | 50 |
1991 | 51 |
1992 | 52 |
1993 | 52 |
1994 | 50 |
1995 | 50 |
1996 | 49 |
1997 | 55 |
ããã®ãã¼ã¿ã使ã£ã¦ããåå¹´ã«æ¯ã¹ã¦å¹´åãå¢ããã®ããæ¸ã£ãã®ããå¤ãããªãã£ãã®ãããSQLã§åºåãã¾ãã試ãã«ãå¤ãããªãã£ãããã¿ã¼ã³ãæ±ãã¦ã¿ã¾ãããã®å ´åããã¼ãã«ããç¾ç¶ç¶æã®å¹´ãã¤ã¾ã93å¹´ã¨95å¹´ãæ±ãã¾ããæç¶ãåè¨èªã®èãæ¹ã«å¾ãã°ã
- 年度ã§æé ã«ã½ã¼ãããã
- ã«ã¼ãããã¦1è¡ãã¤ç´åã®è¡ã®saleåã¨æ¯è¼ãã
ãã¨ããããæ¹ã«ãªãã¾ããããããã¡ãããSQLã§ãããªçºæ³ããã¦ã¯ããã¾ãããããããã¨ãã¯ããSalesããã¼ãã«ã¨ã¯å¥ã«ããåå¹´ã®è¡ããä¿æããéåï¼S2ï¼ãããã1ã¤è¿½å ãã¾ãããã
SELECT year,sale FROM Sales S1 WHERE sale = (SELECT sale FROM Sales S2 WHERE S2.year = S1.year - 1) ORDER BY year;
year sale ----- ----- 1993 52 1995 50
ããµãã¯ã¨ãªå
ã®ãS2.year = S1.year - 1
ãã¨ããæ¡ä»¶ã«ãã£ã¦ãæ¯è¼å¯¾è±¡ã®è¡ã1è¡ããããã¦ãããããã§ããç¸é¢ãµãã¯ã¨ãªã¨èªå·±çµåã¯åå¤å¤æå¯è½ãªå ´åãå¤ãã®ã§ãèªå·±çµåã§æ¸ãã°æ¬¡ã®ããã«ãªãã¾ãã
SELECT S1.year, S1.sale FROM Sales S1, Sales S2 WHERE S2.sale = S1.sale AND S2.year = S1.year - 1 ORDER BY year;
ãã©ã¡ãã®æ¹ãããã©ã¼ãã³ã¹ãè¯ããã¨ããã®ã¯ãä¸æ¦ã«ã¯è¨ãã¾ãããç°å¢ã«ãã£ã¦å·¦å³ãããã®ã§ãæ¯è¼ãã¦ã¿ã¦ãã ããã
ãã§ã¯æ¬¡ã«ãããå¿ç¨ãã¦ãå年度ã«ã¤ãã¦ãåå¹´ã«æ¯ã¹ã¦æé·ããã®ããå¾éããã®ããããã¨ãç¾ç¶ç¶æã ã£ãã®ããä¸åº¦ã«æ±ãã¦ã¿ã¾ãããã