使用的实际查询:
SELECT X.TNO,Y.KID,X.TBALANCE FROM
(SELECT A.TNO,SUM(A.TBAL) TBALANCE,B.CNO FROM TABLE1 A,TABLE2 B
WHERE A.TNO=B.TNO AND B.CPRIM='Y' AND A.TCODE='M'
GROUP BY A.TNO,B.CNO) X, TABLE3 Y
WHERE X.CNO=Y.CNO;
实际结果:
TABLE3.KID TABLE2.TNO TABLE1.SUM(TBAL)
------------------------------------------
R23 34 30
R23 35 40
R55 38 10
R55 39 50
我有3个表格,如下所示
TABLE1:
TNO TBAL TCODE
-----------------
34 30 M
35 40 M
36 50 N
38 10 M
39 50 M
TABLE2:
TNO CNO CPRIM
----------------
34 A3 Y
34 B3 N
34 C1 N
35 D1 Y
35 D2 N
38 E2 Y
38 E4 N
39 F3 Y
39 F5 N
表3:
CNO KID
----------
A3 R23
35 R23
E2 R55
F3 R55
需要以上3个表中的结果,其中TABLE1.TCODE =' M' AND TABLE2.CPRIM =' Y':
TABLE3.KID TABLE2.TNO TABLE1.SUM(TBAL)
------------------------------------------
R23 34 70
R23 35 70
R55 38 60
R55 39 60
请帮我实现上述结果
答案 0 :(得分:0)
您确定要的结果吗?这对我来说没有意义......
这将是我认为的标准聚合:
SELECT C.KID,B.CNO, SUM(A.TBAL)
FROM TABLE3 C
JOIN TABLE2 B ON B.CNO = C.CNO
JOIN TABLE1 A ON A.TNO = B.TNO
WHERE B.CPRIM='Y' AND A.TCODE='M'
GROUP BY C.KID,B.CNO
但要给出结果,你似乎要求......
WITH KIDSUM as (SELECT C.KID, SUM(A.TBAL) as SUMBAL
FROM TABLE3 C
JOIN TABLE2 B ON B.CNO = C.CNO
JOIN TABLE1 A ON A.TNO = B.TNO
WHERE B.CPRIM='Y' AND A.TCODE='M'
GROUP BY C.KID
)
SELECT K.KID,B.TNO, K.SUMBAL
FROM TABLE3 C
JOIN TABLE2 B ON B.CNO = C.CNO
JOIN TABLE1 A ON A.TNO = B.TNO
JOIN KIDSUM K ON K.KID = C.KID
WHERE B.CPRIM='Y' AND A.TCODE='M'