CREATE TABLE A
(ID INT,
GX CHAR (1),
NUM INT,
NUM1 INT
)
GO
INSERT INTO A (ID, GX, NUM, NUM1)
SELECT 1, 'A', 100,50
UNION ALL SELECT 2, 'A', 200,30
UNION ALL SELECT 3, 'A', 300,40
UNION ALL SELECT 3, 'B', 250,20
UNION ALL SELECT 4, 'B', 100,30
UNION ALL SELECT 5, 'B', 200,20
UNION ALL SELECT 5, 'A', 150,25
UNION ALL SELECT 6, 'B', 200,30
GO
SELECT ID, MAX (ISNULL (NNUM, NUM)), SUM (NUM1) FROM
(SELECT M.ID, M.GX, M.NUM, M.NUM1, N.GX AS NGX, N.NUM AS NNUM FROM AM LEFT JOIN AN ON M.ID = N.ID AND N.GX = 'A' ) T
GROUP BY ID |