日期:2014-05-19  浏览次数:20628 次

多表数据加减问题
有以下两个查询语句
SELECT   Item_code,   SUM(in_qty)   AS   sum1
FROM   in_TTBL
WHERE   (indate   > =   DATEADD(mm,   DATEDIFF(mm,   0,   GETDATE()),   0))
GROUP   BY   Item_code
ORDER   BY   Item_code

SELECT   Item_code,   SUM(out_qty)   AS   sum2
FROM   out_TTBL
WHERE   (outdate   > =   DATEADD(mm,   DATEDIFF(mm,   0,   GETDATE()),   0))
GROUP   BY   Item_code
ORDER   BY   Item_code
我希望item_code相同的sum1和sum2相加或相减用一句sql语句实现,请帮帮忙,谢谢!

------解决方案--------------------
Select A.Item_code, A.sum1 + B.sum2 As sum3
From
(SELECT Item_code, SUM(in_qty) AS sum1
FROM in_TTBL
WHERE (indate > = DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0))
GROUP BY Item_code
) A
Inner Join
(
SELECT Item_code, SUM(out_qty) AS sum2
FROM out_TTBL
WHERE (outdate > = DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0))
GROUP BY Item_code
) B
On A.Item_code = B.Item_code