我做了与@JohnBevan 相同的选择,但做了一些更改(没有在主选择上使用分组,他也忘记命名内部选择列)
DECLARE @table1 TABLE (bln INT, thn INT, qty1 INT)
INSERT INTO @table1 SELECT 1,2014,10
INSERT INTO @table1 SELECT 1,2014,20
INSERT INTO @table1 SELECT 2,2014,30
INSERT INTO @table1 SELECT 3,2014,40
INSERT INTO @table1 SELECT 2,2014,50
INSERT INTO @table1 SELECT 4,2014,60
DECLARE @table2 TABLE (bln INT, thn INT, qty2 INT)
INSERT INTO @table2 SELECT 3,2014,200
INSERT INTO @table2 SELECT 5,2014,400
INSERT INTO @table2 SELECT 2,2014,100
INSERT INTO @table2 SELECT 2,2014,500
INSERT INTO @table2 SELECT 4,2014,300
INSERT INTO @table2 SELECT 6,2014,600
CREATE VIEW NewView AS
SELECT COALESCE(T1.bln, T2.bln) AS bln
, COALESCE(T1.thn, T2.thn) AS thn
, COALESCE(T1.qty1, 0) AS qty1
, COALESCE(T2.qty2, 0) AS qty2
FROM (
SELECT bln, thn, SUM(qty1) AS qty1
FROM @table1
GROUP BY bln, thn
) AS T1
FULL JOIN (
SELECT bln, thn, SUM(qty2) AS qty2
FROM @table2
GROUP BY bln, thn
) AS T2
ON T1.bln = T2.bln
AND T1.thn = T2.thn
SQLFiddle:http ://sqlfiddle.com/#!6/a3e2b/1