SQL平常問題和技巧1(列變行、自定義查詢結構、將字符串分割爲多條記錄)

  1.ORACLE列變行加合計:oracle

查詢結果爲函數

 

 


 1 SELECT
 2     nvl( F, '合計' ) F,
 3     sum( S1 ) S1,
 4     sum( S2 ) S2,
 5     sum( S3 ) S3
 6 FROM
 7     (SELECT
 8     F,
 9     sum( decode( S, 'S1', N, NULL ) ) S1,
10        sum( decode( S, 'S2', N, NULL ) ) S2,
11        sum( decode( S, 'S3', N, NULL ) ) S3    
12 FROM
13     LQG_TEST    
14 GROUP BY
15     F)
16 GROUP BY
17     rollup (
18     F)

 2.自定義查詢結構,場景以下:spa

查詢語文,數學,英語,科學四門學科的分數,可是表裏只有數學和英語。如圖:3d

查詢結果爲:code

看看SQL吧(nvl函數用於oracle):regexp

 1 SELECT
 2     TMP1.COURSE AS COURSE,
 3     NVL ( TMP2.SCORE, 0 ) AS SCORE 
 4 FROM
 5     (
 6     SELECT
 7         '語文' COURSE 
 8     FROM
 9     DUAL UNION ALL
10     SELECT
11         '數學' COURSE 
12     FROM
13     DUAL UNION ALL
14     SELECT
15         '英語' COURSE 
16     FROM
17     DUAL UNION ALL
18     SELECT
19         '科學' COURSE 
20     FROM
21     DUAL 
22     ) TMP1
23     LEFT JOIN (
24     SELECT
25     CASE
26             
27         WHEN
28             COURSE = 'CHINESE' THEN
29                 '語文' 
30                 WHEN COURSE = 'MATH' THEN
31                 '數學' 
32                 WHEN COURSE = 'ENGLISH' THEN
33                 '英語' 
34                 WHEN COURSE = 'SCIENCE' THEN
35                 '科學' 
36             END AS COURSE,
37             SCORE 
38         FROM
39         LGQ_TEST 
40     ) TMP2 ON TMP1.COURSE = TMP2.COURSE

 3.將字符串按某字符分割爲多條記錄blog

1 SELECT
2     REGEXP_SUBSTR( '趙-錢-孫-李', '[^-]+', 1, ROWNUM ) 
3 FROM
4     dual CONNECT BY ROWNUM <= LENGTH( '趙-錢-孫-李' ) - LENGTH(
5     regexp_replace( '趙-錢-孫-李', '-', '' )) + 1

相關文章
相關標籤/搜索