TSQL - 选择休假日期在发票范围内的数据的最佳方式

时间:2009-05-13 17:17:55

标签: tsql

背景:我有一个工资单系统,只有在支付的发票范围内,才会支付休假。因此,如果发票涵盖过去2周,则只需在最近2周内完成付款。

我想写一个sql查询来选择离开。

假设一个名为DailyLeaveLedger的表格,其中包含LeaveDatePaid标志。 假设一个名为Invoice的表是WeekEnding字段和NumberWeeksCovered字段。

现在假设截止日期为15/05/09,NumberWeeksCovered = 2,且LeaveDate为11/05/09。

这是我想要写它的一个例子。实际的查询非常复杂,但我希望LeaveDate检查是一个In子查询。

SELECT * 
FROM DailyLeaveLedger 
WHERE Paid = 0 AND
      LeaveDate IN (SELECT etc...What should this be to do this)

不确定我的提法是否可行?

马尔科姆

1 个答案:

答案 0 :(得分:3)

所以对于某些发票,LeaveDate应介于(WeekEnding-NoOfWeeksCovered)和(WeekEnding)之间?

如果我理解正确,你可以使用EXISTS()子查询,如下所示:

SELECT * 
FROM DailyLeaveLedger dl
WHERE Paid = 0 AND
      EXISTS (SELECT *
              FROM Invoice i
              WHERE DateAdd(week,-i.NumberOfWeeksCovered,i.WeekEnding) < dl.LeaveDate 
              AND i.WeekEnding > dl.LeaveDate
              /* and an extra clause in here to make sure
              the invoice is for the same person as the dailyleaveledger row */
              )