我有以下选项从日志中选择并分组到分钟(不包括秒和milisec):
SELECT DATEPART(YEAR, [Date]) AS YEAR, DATEPART(MONTH, [Date]) AS MONTH,
DATEPART(DAY, [Date]) AS DAY, DATEPART(HOUR, [Date]) AS HOUR,
DATEPART(MINUTE, [Date]) AS MIN, COUNT(*) AS COUNT
FROM [database].[dbo].[errorlog]
GROUP BY DATEPART(YEAR, [Date]), DATEPART(MONTH, [Date]), DATEPART(DAY, [Date]),
DATEPART(HOUR, [Date]), DATEPART(MINUTE, [Date])
ORDER BY DATEPART(YEAR, [Date]) DESC, DATEPART(MONTH, [Date]) DESC,
DATEPART(DAY, [Date]) DESC, DATEPART(HOUR, [Date]) DESC,
DATEPART(MINUTE, [Date]) DESC;
但是正如你可以看到的那样只是为了获得一个计数,所以我想知道是否有更好的方法对它进行分组,所以我按年,月,日和小时分组到几分钟? / p>
答案 0 :(得分:2)
这应该有效:
select CAST([Date] AS smalldatetime) as time_stamp, count(*) as count
FROM [database].[dbo].[errorlog]
group by CAST([Date] AS smalldatetime)
order by CAST([Date] AS smalldatetime) desc;
对此答案的评论后更新:
select dateadd(second,-datepart(ss,[Date]),[Date]) as time_stamp, count(*) as count
FROM [database].[dbo].[errorlog]
group by dateadd(second,-datepart(ss,[Date]),[Date])
order by dateadd(second,-datepart(ss,[Date]),[Date]) desc ;
第一个解决方案将时间戳向上舍入到最近的分钟。我意识到这不是OP想要的。
因此,第二个解决方案只是从时间戳中减去seconds
部分,并将时间戳保留为秒zero
(假设[日期]没有小数秒)
答案 1 :(得分:0)
DATEADD(minute,DATEDIFF(minute,'20010101',[Date]),'20010101')
应将所有Date
列值舍入到最接近的分钟。所以:
SELECT DATEADD(minute,DATEDIFF(minute,'20010101',[Date]),'20010101'),
COUNT(*) AS COUNT
FROM [database].[dbo].[errorlog]
GROUP BY DATEADD(minute,DATEDIFF(minute,'20010101',[Date]),'20010101')
ORDER BY DATEADD(minute,DATEDIFF(minute,'20010101',[Date]),'20010101') DESC;
(如果您想进一步减少重复,可以将此表达式移动到子查询中)
答案 2 :(得分:0)
你可以做这样的事情来获得
declare @now datetime
set @now = GETDATE()
select dateadd(minute, mm, @now) as date, c from (
select DATEDIFF(minute, @now, [Date]) as mm, COUNT(1) as c
from [database].[dbo].[errorlog]
group by DATEDIFF(minute, @now, [Date])
) t