2010-12-09 21 views
1

我已經嘗試過,但我無法弄清楚這一點。我有一個表事務(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等等等 我現在我需要使用遞歸選擇,但我寫的東西不會產生正確的時間框架。 我已經寫到目前爲止,這是爲了查找一段時間的交易的T-SQL遞歸

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的結果的查詢

+0

你想要360個不同的結果集嗎? – gbn 2010-12-09 08:49:41

回答

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

+0

你的答案是100%正確的。只是團隊是這樣的GROUP BY t.transaction_person_Id,w.WeekStartMidnight,w.WeekEndMidnight非常感謝 – 2010-12-09 09:08:09