Sql 从两个表中减去值

Sql 从两个表中减去值,sql,sql-server,Sql,Sql Server,我有如下两张桌子 预测 Account,Date,Type,Hours 123456,11/2/2013,REG,40 123456,11/9/2013,REG,32 工作 Account,Date,Type,Hours 123456, 11/2/2013,REG,8 123456, 11/2/2013,REG,10 123456, 11/2/2013,REG,10 123456, 11/2/2013,REG,10 123456, 11/9/2013,VAC,8 123456, 11/9/

我有如下两张桌子

预测

Account,Date,Type,Hours

123456,11/2/2013,REG,40
123456,11/9/2013,REG,32
工作

Account,Date,Type,Hours

123456, 11/2/2013,REG,8
123456, 11/2/2013,REG,10
123456, 11/2/2013,REG,10
123456, 11/2/2013,REG,10
123456, 11/9/2013,VAC,8
123456, 11/9/2013,REG,8
123456, 11/9/2013,REG,8
123456, 11/9/2013,REG,8
我需要以下输出

123456
11/2/2013
REG 40 - 38 = 2
11/9/2013
REG 32 - 24 = 8
Vac 0 - 8 = -8

我基本上需要预测表和工作表之间的差异。用户将输入日期2013年11月9日,结果将包括该日期和之前7天,因此在本例中,将包括2013年11月9日和2013年11月2日。我还只希望在预测表中找到的员工可以使用此查询。它使用完全外部联接,因为两个表中的数据可能不同。类型可能不同:

declare @date date = '11/9/2013'

select f.Account, f.[Date],
case when f.[Type] is not null then f.[Type] else w.[Type] end [Type],
ISNULL(f.Hours, 0) - ISNULL(w.Hours, 0) Hours
from
    (select Account, [Date], [Type], SUM(Hours) Hours
    from Forecasted
    where [Date] >= dateadd(dd, -7, @date) and [Date] <= @date
    group by Account, [Date], [Type]) f
full outer join
    (select Account, [Date], [Type], SUM(Hours) Hours
    from Worked
    where [Date] >= dateadd(dd, -7, @date) and [Date] <= @date
    group by Account, [Date], [Type]) w
on f.Account = w.Account and f.[Date] = w.[Date] and f.[Type] = w.[Type]

这第一部分可能是一个评论,但我还没有足够的声誉来评论

那么在工作表中,4天的日期是相同的,那么代表工作周的日期也是一样的吗?看起来你需要对给定日期的每个条目的工时进行求和,然后将其与预测的工时进行比较,是吗

假设是这样,您首先需要用户以定义的日期表单输入。然后:

Select f.Hours + ' - ' + SUM(select hours from Worked where date=USER_INPUT) + ' = ' + f.hours-w.hours
from forcasted f
outer join  worked w
on f.account = w.account
where f.date=USER_INPUT

这显然是某种伪代码,但希望这能让您了解如何实现这一点

我试着用工会来做这件事,但没有成功。我的部分查询确实使用了一个联合来返回预测小时数,然后返回工作小时数。这很好,这是我得到的2个问题之间的区别,我得到了Stucketdit你的问题,以显示你尝试的联合查询和你得到的结果。这可能会避开那些想结束这个问题的人。投票赞成关于评论和声誉的评论。感谢,谢谢。这很有效。多谢各位