我面臨着我的查詢的邏輯問題。完全加入羣組
我有兩個表Table1
和Table2
,其中Table1
組成:
value
要被總計Id
由Code
被分組持有外國關鍵Table2
而且Table2
由
Code
Des
的代碼
我試圖做的是文字說明,由Table1.Id
組成,完全加入Table2.Code
,但是,f或每個結果組,我希望顯示查詢生成的每個組的Table2中的所有行。
示例代碼:
SELECT
Table2.Code, Table1.Id, Table2.DES,
SUM(Table1.Value) AS SUM_VAL
FROM
(
SELECT 'A' AS Code, 1 AS Id, 10 AS Value FROM DUAL UNION
SELECT 'A' AS Code, 2 AS Id, 20 AS Value FROM DUAL UNION
SELECT 'B' AS Code, 1 AS Id, 10 AS Value FROM DUAL UNION
SELECT 'B' AS Code, 1 AS Id, 30 AS Value FROM DUAL UNION
SELECT 'B' AS Code, 2 AS Id, 50 AS Value FROM DUAL UNION
SELECT 'C' AS Code, 1 AS Id, 40 AS Value FROM DUAL UNION
SELECT 'C' AS Code, 2 AS Id, 60 AS Value FROM DUAL UNION
SELECT 'D' AS Code, 1 AS Id, 20 AS Value FROM DUAL
) Table1
FULL JOIN
(
SELECT 'A' AS Code, 'This is A' AS DES FROM DUAL UNION
SELECT 'B' AS Code, 'This is B' AS DES FROM DUAL UNION
SELECT 'C' AS Code, 'This is C' AS DES FROM DUAL UNION
SELECT 'D' AS Code, 'This is D' AS DES FROM DUAL
) Table2
ON Table1.Code = Table2.Code
GROUP BY
Table2.Code, Table1.Id, Table2.DES
ORDER BY
Table2.Code, Table1.Id ASC
結果:
A 1 This is A 10
A 2 This is A 20
B 1 This is B 40
B 2 This is B 50
C 1 This is C 40
C 2 This is C 60
D 1 This is D 20
要求的結果:
A 1 This is A 10
A 2 This is A 20
B 1 This is B 40
B 2 This is B 50
C 1 This is C 40
C 2 This is C 60
D 1 This is D 20
D 2 This is D 0 <- This is the target
coalesce(Table1.Code,Table2.Code)in select and group by? – jarlh
這與這個問題有什麼關係? – simsim
當table1中沒有命中時,改進了完整的外部聯接結果。 – jarlh