T-SQL递归,以便在一段时间内查找事务

时间:2010-12-09 08:30:58

标签: sql sql-server tsql select recursion

我已经尝试但我无法弄清楚这一点。我有一个表事务(transaction_ID,transaction_Person_ID,Transaction_Date等)。  我想要的是返回去年每周超过3笔交易的所有transaction_person_ID。这意味着我必须检查1-1-10到7-1-10,看看有人在那7天的时间内有超过3笔交易,然后是2-1-10到8-1-10然后3-1 -10到9-1-10等 我现在需要使用递归选择,但我写的东西不能产生正确的时间范围。 到目前为止我写的是这个

WITH Dates AS (
        SELECT
         [Date] = CONVERT(DATETIME,'01/01/2010')
        UNION ALL SELECT
         [Date] = DATEADD(DAY, 1, [Date])
        FROM
         Dates
        WHERE
         Date < '12/31/2010'
)

SELECT transaction_person_Id FROM transactions
JOIN DATES
ON transactions.transaction_date = dates.date
where transactions.Transaction_Date between dateadd(DAYOFYEAR,-7,dates.date) and dates.date
group by transaction_person_Id
having count(transaction_person_ID) >= 4
OPTION (MAXRECURSION 2000)

非常感谢

PS: 简单来说,我需要做的就是这个

 select transaction_person_ID from transactions
    where Transaction_Date between '2010-01-01' and '2010-01-07'
    group by transaction_person_Id
    having count(transaction_person_ID) >= 4

然后

 select transaction_person_ID from transactions
    where Transaction_Date between '2010-01-02' and '2010-01-08'
    group by transaction_person_Id
    having count(transaction_person_ID) >= 4

。 。 。 。 。 直到它

 select transaction_person_ID from transactions
    where Transaction_Date between '2010-12-25' and '2010-12-31'
    group by transaction_person_Id
    having count(transaction_person_ID) >= 4

我需要获得这365个查询的结果

1 个答案:

答案 0 :(得分:0)

这将给出一个带有人和周的结果集,而不是360结果集

WITH Weeks
     AS (
        SELECT
           CONVERT(DATETIME,'01 Jan 2010') AS WeekStartMidnight, 
           CONVERT(DATETIME,'08 Jan 2010') AS WeekEndMidnight
        UNION ALL
        SELECT
           DATEADD(day, 1, WeekStartMidnight),
           DATEADD(day, 1, WeekEndMidnight)
        FROM
            Weeks
        WHERE
           WeekEndMidnight < '31 Dec 2010'
)
SELECT
   t.transaction_person_Id,
   w.WeekStartMidnight, w.WeekEndMidnight
FROM
   weeks w
   JOIN
   transactions t ON t.Transaction_Date >= w.WeekStartMidnight AND t.Transaction_Date < w.WeekEndMidnight
GROUP BY
   t.transaction_person_Id
HAVING
   count(*) >= 4 --COUNT(t.transaction_person_Id) = same
OPTION
   (MAXRECURSION 365)

如果你想要360个结果集,那么在“周”派生表中每行使用WHILE或CURSOR