DECLARE @A TABLE (ID INT ,NAME VARCHAR(10) ,AGE INT)
INSERT INTO @A SELECT 1
,'张三',
20
UNION SELECT 2,
'马六',
21
UNION SELECT 5,
'王二',
22
DECLARE @B TABLE (ID INT ,ID1 VARCHAR(10) ,ID2 INT)
INSERT INTO @B SELECT 1 , '化学',
3
UNION SELECT 1 , '化学',
2
UNION SELECT 5,
'物理',
6
SELECT A.ID,A.NAME,A.AGE,B.COL1,(CASE C.ID1
WHEN '化学' THEN C.COL2 ELSE 0 END) AS 化学
FROM @A
A ,(SELECT ID,SUM(ISNULL(ID2,0)) AS COL1 FROM @B
GROUP BY ID) B,(SELECT ID,ID1 ,SUM(ISNULL(ID2,0))
AS COL2 FROM @B GROUP BY ID,ID1) C WHERE A.ID=B.ID AND A.ID=C.ID