[code=sql]USE tempdb
IF OBJECT_ID('TEST1') IS NOT NULL
DROP TABLE TEST1;
GO
CREATE TABLE TEST1
(
name nvarchar(10),
pal nvarchar(10)
);
GO
IF OBJECT_ID('TEST2') IS NOT NULL
DROP TABLE TEST2;
GO
CREATE TABLE TEST2
(
date date,
name nvarchar(10),
[in] int
);
GO
IF OBJECT_ID('TEST3') IS NOT NULL
DROP TABLE TEST3;
GO
CREATE TABLE TEST3
(
date date,
name nvarchar(10),
[out]int
);
GO
INSERT INTO TEST1 VALUES
('p1','大米'),
('p2','小麦'),
('p3','高粱'),
('p4','玉米'),
('p5','小米');
GO
INSERT INTO TEST2 VALUES
('2012-9-1','p1',10),
('2012-9-2','p2',30),
('2012-9-3','p3',50),
('2012-9-4','p4',20),
('2012-9-5','p5',15);
GO
INSERT INTO TEST3 VALUES
('2012-9-1','p1',25),
('2012-9-2','p4',35),
('2012-9-3','p1',50),
('2012-9-4','p4',40),
('2012-9-5','p2',10);
GO
SELECT A.name,A.pal,
SUM(ISNULL(B.[in],0)) AS [in],
SUM(ISNULL(C.[out],0)) AS [out]
FROM TEST1 AS A
LEFT JOIN TEST2 AS B
ON A.name = B.name
LEFT JOIN TEST3 AS C
ON A.name = C.name
GROUP BY A.name,A.pal
/*
name pal in out
---------- ---------- ----------- -----------
p1 大米 20 75
p3 高粱 50 0
p2 小麦 30 10
p5 小米 15 0
p4 玉米 40 75
(5 行受影响)
*/ [/code] |