按日期和条目数分组

时间:2014-08-28 17:12:44

标签: sql tsql date statistics

我做得很简短,表格如下:

| id (int) | registerDate (DATETIME)
|----------|-----------------
| 1        | 2014-07-29 12:00:00
| 2        | 2014-08-01 12:00:00
| 3        | 2014-08-01 12:00:00
| 4        | 2014-08-01 12:00:00
| 5        | 2014-08-02 12:00:00
| 6        | 2014-08-02 12:00:00
| 7        | 2014-08-04 12:00:00

如果今天是2014-08-05,我想要这样的结果:

| registerDate (DATETIME) | count (int)
| 2014-08-04              | 1
| 2014-08-03              | 0
| 2014-08-02              | 2
| 2014-08-01              | 1
| 2014-07-31              | 0
| 2014-07-30              | 0
| 2014-07-29              | 1

所以我想要过去一周(每天)的注册用户数。 我试图在谷歌上找到它(失败) - 但是,我希望你能帮忙。

2 个答案:

答案 0 :(得分:1)

SELECT registerDate, count(registerDate) FROM [TABLE] WHERE
registerDate between (GETDATE()-7) and GETDATE()   
group by registerDate  
order by registerDate desc

这将采用如下表格:

2   |1905-06-26 00:00:00.000
4   |2014-08-03 00:00:00.000
5   |2014-08-02 00:00:00.000
1   |2014-08-01 00:00:00.000
3   |2014-07-01 00:00:00.000
6   |2010-07-01 00:00:00.000
7   |2015-07-01 00:00:00.000
8   |2014-08-28 00:00:00.000
9   |2014-08-26 00:00:00.000
10  |2014-08-26 00:00:00.000

并创建:

2014-08-28 00:00:00.000 |   1
2014-08-26 00:00:00.000 |   2

问题在于它没有显示表中没有的日子。 给我一点时间,我会有更新版本。

编辑:

现在更复杂的......

-- Declare how far back you want to go
DECLARE @DAYSBACK int = 6

-- Select into a temptable
select CONVERT(date, registerDate) as RegDate, count(registerDate) as DateCount 
  INTO #temptable 
  from Temp where registerDate between (GETDATE()-6) and GETDATE()
  group by registerDate order by registerDate desc

-- Check to see if exists if not, insert row
WHILE @DAYSBACK >= 0 BEGIN
    IF NOT EXISTS (select top 1 1 from #temptable 
                   where RegDate= CONVERT(date, (GETDATE()-@DAYSBACK))
                   group by RegDate)
        INSERT INTO #temptable values ((GETDATE()-@DAYSBACK), 0)
    SET @DAYSBACK = @DAYSBACK -1
END

-- Select what you want
select * from #temptable order by RegDate desc

-- Drop the table you created.
DROP TABLE #temptable

使用与上面相同的表格,它将输出:

Register Date | Date Count
--------------------------
2014-08-28    | 1
2014-08-27    | 0
2014-08-26    | 2
2014-08-25    | 0
2014-08-24    | 0
2014-08-23    | 0
2014-08-22    | 0

答案 1 :(得分:0)

尝试这样的事情:

select registerDate  = convert(date,t.registerDate) ,
       registrations = count(*)
from dbo.my_special_registration_table t
where t.registrationDate >= dateadd(day,-7,convert(date,getdate()))
group by convert(date,t.registerDate)
order by 1

如果您尝试使用datediff()

之类的内容过滤掉7天以内的注册
where datediff(day,t.registrationDate,getdate()) <= 7

您将列registrationDate转换为表达式。因此,查询优化器无法使用可能适用的任何索引,从而强制进行表扫描。如果你的表很大,性能可能是......次优。