每秒事务数

时间:2016-04-01 18:18:27

标签: sql sql-server

我需要每秒显示每秒特定列事务数。

以下查询适用于每分钟。

Select DISTINCT column1 AS Event, Count( column1 ) AS count,
DateAdd(MINUTE, DateDiff(MINUTE, 0, [dateTimeColumn]), 0) as Time
From table
  Group By column1 ,DateAdd(MINUTE, DateDiff(MINUTE, 0, [dateTimeColumn]), 0)

测试数据如下:

Event   Time
A        21:01:01
A        21:01:02
A        21:02:01

结果为

Event    Count  Time
A         2     21:01
A         1     21:02

结果应该是秒级

Event    Count  Time
A         1     21:01:01
A         1     21:01:02
A         1     21:02:01

但我现在需要每秒的交易而不是分钟。当我给DateDiff(第二个......)时,它会给出错误作为日期溢出错误。

请建议

1 个答案:

答案 0 :(得分:1)

请改为尝试:

;WITH CTE_MinTime AS (SELECT MIN(dateTimeColumn) AS min_time FROM Table)
SELECT
    T.column1 AS Event,
    COUNT(*) AS [count],
    DATEADD(SECOND, DATEDIFF(SECOND, MT.min_time, T.dateTimeColumn), MT.min_time) AS [Time]
FROM
    CTE_MinTime MT
CROSS JOIN Table T
GROUP BY
    T.column1,
    DATEADD(SECOND, DATEDIFF(SECOND, MT.min_time, T.dateTimeColumn), MT.min_time)

问题在于,当你执行DATEDIFF时,它会计算1900-01-01的秒数,这对于默认数据类型来说太大了。