从2个表中减去值

时间:2013-12-02 23:50:02

标签: 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/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日。我也只想要在预测表中找到的员工

2 个答案:

答案 0 :(得分:1)

您可以使用此查询。它使用全外连接,因为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]

答案 1 :(得分:1)

这第一部分应该是评论,但我还没有足够的声誉来发表评论。

因此,在工作表中,日期与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

这显然是伪代码,但希望这会让你知道如何处理这个问题。

相关问题