我有2张桌子
warehouse_1
item qty
--------
3001 1
3003 3
3004 1
3006 2
warehouse_2
item qty
----------
3001 2
3002 3
3006 3
3008 6
我想将这两个表合并为第三个,并添加相同项目的数量,如此
warehouse_3
item qty
-----------
3001 3
3002 3
3003 3
3004 1
3006 5
3008 6
如何使用SQL Server实现此目的?
答案 0 :(得分:4)
您可以使用UNION
来实现它。首先,你必须联合所有数据(两个表)和使用子查询,你可以使用GROUP BY
进行分组,并使用SUM
函数添加总数。
SELECT Item, SUM(qty) as Qty FROM
(
SELECT Item, qty FROM warehouse_1
UNION
SELECT Item, qty FROM warehouse_2
) as a
GROUP BY item;
详细了解UNION
:
详细了解GROUP BY
子句:(您也可以在那里找到SUM
。)
答案 1 :(得分:0)
请尝试:
select item,sum(qty) from(
select item, Qty from warehouse_1
UNION
select item, Qty from warehouse_2
)x
group by item
答案 2 :(得分:0)
CREATE OR REPLACE VIEW warehouse_3 as
SELECT coalesce(w1.item,w2.item) as item, w1.qty+w2.qty as qty
FROM warehouse_1 as w1
OUTER JOIN warehouse_2 as w2
ON w1.item = w2.item;
假设项目是唯一的。某些数据库中合并 nvl 。 然后你可以打电话:
select * from warehouse_3;
它将返回总和。
此外,如果您更改W1或W2中的某些数量,它将在W3中自动更正
答案 3 :(得分:0)
你可以试试这个
SELECT item , SUM(qty)
FROM (
SELECT item, qty
FROM warehouse_1
UNION
SELECT item, qty
FROM warehouse_2
) AS U GROUP BY item
答案 4 :(得分:0)
试试这个:
create table tbl1(item int,qty int)
INSERT INTO tbl1
VALUES(3001,1),(3003,3),(3004,1),(3006,2)
create table tbl2(item int,qty int)
INSERT INTO tbl2
VALUES(3001,2),(3002,3),(3006,3),(3008,6)
select isnull(t1.item,t2.item) as item,isnull(t1.qty,0)+isnull(t2.qty,0) as qty from tbl1 t1 full outer join tbl2 t2 on t1.item =t2.item
order by 1