我将这个名为Table1
的表格如下:
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)
之后MIN(Date)
到DATEADD(day,30,MIN(DATE))
之后30天 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}}
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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)
答案 3 :(得分: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