1

我有以下从日志和组中选择到分钟(不包括秒和毫秒):

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;

但是正如你所看到的,只是为了计数而产生了很多模糊,所以我想知道是否有更好的方法来分组它,以便我根据年、月、日和小时将其分组到分钟?

4

3 回答 3

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(假设 [Date] 没有小数秒)

于 2013-10-02T08:10:33.210 回答
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;

(如果您想进一步减少重复,可以将此表达式移动到子查询中)

于 2013-10-02T08:10:29.137 回答
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
于 2013-10-02T08:10:42.810 回答