我有一个表,其中包含每个帐户的帐户交易,我写了一个查询,告诉我帐户何时支付了一个月,而不是基于参数MonthID(来自cal查找表)的下一个帐户
DECLARE @MonthID INT
SET @MonthID = 128
SELECT AccountNo, Emp,
FROM Table1 AS t INNER JOIN
tblcal AS cl ON t.date = cl.Date
WHERE cl.MonthID = @MonthID
EXCEPT
SELECT AccountNo, Emp,
FROM Table1 AS t INNER JOIN
tblcal AS cl ON t.date = cl.Date
WHERE cl.MonthID = @MonthID+1
查询非常适合获取指定月份的记录,但我需要查看一年中每个月的这个记录,并且不知道如何将该要求考虑在内?
光标是最好的方法吗?我读过很多关于游标的负面消息?
目前它返回的数据如下:
MonthID | SkippedPay
128 | 12445
(因为我对帐号进行了计算)
我需要的是在过去12个月内获得它,所以与上面相同,但是有12个月的数据,这是让我想到每个月都要经过游标并填充表格的原因吗?
MonthID | SkippedPay
128 | 12445
129 | 1256
答案 0 :(得分:0)
以下方法如何:
根据下个月的数据,left join
一个月的数据集,并返回下个月没有相应数据的行。
DECLARE @MonthID INT
SET @MonthID = 128
SELECT MonthA.AccountNo, MonthA.Emp FROM
(SELECT AccountNo, Emp, cl.MonthID as [Month]
FROM Table1 AS t INNER JOIN
tblcal AS cl ON t.date = cl.Date
WHERE cl.MonthID >= @MonthID-12 and cl.MonthID <= @MonthID) AS MonthA
LEFT JOIN
(SELECT AccountNo, Emp, cl.MonthID as [Month]
FROM Table1 AS t INNER JOIN
tblcal AS cl ON t.date = cl.Date
WHERE cl.MonthID >= @MonthID-11 and and cl.MonthID <= @MonthID+1) AS MonthB on MonthA.AccountNo = MonthB.AccountNo AND MonthA.Emp = MonthB.Emp AND (MonthA.[Month]+1) = Monthb.[Month]
WHERE MonthB.AccountNo IS NULL
p.s。:您的查询中出现语法错误:“Emp”,没有以下字段。