任何人都可以告诉子查询找到2个不同表中2个字段的差异作为单个值

时间:2014-01-22 13:16:15

标签: sql sql-server

我已经尝试了下面的内容,我能够得到答案,但我需要将其称为前端的单个查询,因此任何一个都可以替代它。

我不需要这个SP:

DECLARE @ven INT; Declare @dai int;

select @ven= SUM(po) from Vendortable where VendorName ='HP' and Date  = '2014-01-22'

select @dai= SUM(completepo) from Daily_Volume_Tracker where AccountVendorName = 'HP' and date > = '2014-01-22'

  select @ven - @dai

结果:

Result
--------
5831

2 个答案:

答案 0 :(得分:2)

脱离我的头脑,这样的事情可能有用:

WITH CTE AS
(
   select
   (select SUM(po) from Vendortable where VendorName ='HP' and Date  = '2014-01-22') as Val1
   ,(select SUM(completepo) from Daily_Volume_Tracker where AccountVendorName = 'HP' and date > = '2014-01-22' as Val2
)

Select Val1 - Val2 From CTE

我喜欢使用常用的表格表达式。

答案 1 :(得分:1)

尝试这个简单的子查询

Select 
(
    (
        select SUM(po) as Ven from Vendortable where VendorName ='HP' and Date  = '2014-01-22'
    )
    -
    (
        select SUM(completepo) as Dai from Daily_Volume_Tracker where AccountVendorName = 'HP' and date > = '2014-01-22'
    )
) Result