背景:我有一个工资单系统,只有在支付的发票范围内,才会支付休假。因此,如果发票涵盖过去2周,则只需在最近2周内完成付款。
我想写一个sql查询来选择离开。
假设一个名为DailyLeaveLedger
的表格,其中包含LeaveDate
和Paid
标志。
假设一个名为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)
不确定我的提法是否可行?
马尔科姆
答案 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 */
)