有意思的SQL案例1
阿新 • • 發佈:2018-11-12
如下兩個表
Table 1 ============== fn_a1 fn_a2 ============== A 3 B 1 C 2 -------------- Table 2 ====================== fn_b1 fn_b2 fn_b3 ====================== 1 A A1 2 B B1 ---------------------- 結果 ====================================== fn_a1 fn_a2 fn_b1 fn_b2 fn_b3 ====================================== A 3 1 A1 1 A 3 2 A 3 3 B 1 2 B1 1 C 2 1 C 2 2 --------------------------------------
提問:
使用 Table 1,Table 2 ,求得如下結果集
SELECT a.fn_a1 , a.fn_a2 , b.fn_b1 , b.fn_b2 , c.lv fn_b3 FROM Table_1 a INNER JOIN (SELECT 1 lv UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 ) c ON a.fn_a2 >= c.lv LEFT OUTER JOIN Table_2 b ON a.fn_a1 = b.fn_b2 AND c.lv = 1 ORDER BY a.fn_a1, c.lv ;