2009-09-17 40 views
0

我有這樣的表稱爲Table1如下:COUNT帶日期區間

UserID Date 
    1  01/01/09 
    1  14/01/09 
    1  25/01/09 
    1  01/02/09 
    1  15/02/09 
    2  02/02/09 
    2  15/02/09 

我試圖返回計數的MIN(Date) 30天之間倍MIN(Date)這是DATEADD(day,30,MIN(DATE))後的數字結果。因此,這將是這個樣子:

UserID Count 
    1  3 
    2  2 

下面這段代碼是錯誤的,但它表達了什麼,我想實現:

SELECT COUNT(1) AS Count 
FROM Table1 
GROUP BY UserID 
WHERE Date BETWEEN MIN(Date) AND DATEADD(day,30,MIN(DATE)) 

回答

1
SELECT a.UserID, COUNT(a.UserID) AS [Count] 
FROM Table1 AS a 
    INNER JOIN 
    (
     SELECT UserID, MIN([Date]) AS MinDate 
     FROM Table1 
     GROUP BY UserID 
    ) AS b 
     ON a.UserID = b.UserID 
WHERE [Date] BETWEEN MinDate AND DATEADD(day, 30, MinDate) 
GROUP BY a.UserID 
+0

歡呼隊友!!!! – super9 2009-09-17 11:59:27

1

試試這個

DECLARE @table TABLE(
     UserID INT, 
     DDate DATETIME 
) 

INSERT INTO @table (UserID,DDate) SELECT 1, '01 Jan 2009' 
INSERT INTO @table (UserID,DDate) SELECT 1, '14 Jan 2009' 
INSERT INTO @table (UserID,DDate) SELECT 1, '25 Jan 2009' 
INSERT INTO @table (UserID,DDate) SELECT 1, '01 Feb 2009' 
INSERT INTO @table (UserID,DDate) SELECT 1, '15 Feb 2009' 
INSERT INTO @table (UserID,DDate) SELECT 2, '02 Feb 2009' 
INSERT INTO @table (UserID,DDate) SELECT 2, '15 Feb 2009' 


SELECT t.UserID, 
     COUNT(t.UserID) 
FROM @table t INNER JOIN 
     (
      SELECT UserID, 
        MinDate, 
        DATEADD(dd, 30, MinDate) MinDataAdd30 
      FROM (
         SELECT UserID, 
           MIN(DDate) MinDate 
         FROM @table 
         GROUP BY UserID 
        ) MINDates 
     ) DateRange ON t.UserID = DateRange.UserID 
WHERE t.DDate BETWEEN DateRange.MinDate AND DateRange.MinDataAdd30 
GROUP BY t.UserID 
0

我想你」你需要使用子查詢來獲取最短日期。我已經在 以下顯示它作爲一個單獨的查詢到一個變量,因爲我可能會把它變成一個表值函數。

DECLARE @STARTDATE DATETIME 

SELECT @STARTDATE = MIN(DATE) FROM Table1 

SELECT COUNT(1) AS Count 
FROM Table1 
GROUP BY UserID 
WHERE Date BETWEEN @STARTDATE AND DATEADD(day,30,@STARTDATE) 
0

我會做這樣的:

select a.UserID, count(case when DDate - MinDate <= 30 then 1 end) as Count 
from (
    select UserID, min(DDate) MinDate 
    from Table1 
    group by UserID 
) a 
inner join Table1 t on a.UserID = t.UserID 
group by a.UserID