SQL-获取具有相同的创建日期datetime至分钟的行

时间:2019-05-15 21:29:19

标签: sql-server datetime join timestamp

我有一个表,其数据如下:

   id  question_id Created_dt           secondary_question_id
  --------------------------------------------------------
   1     71        2016-03-12 16:33:00        123
   2     71        2016-03-12 16:33:09        124
   3     71        2016-03-12 16:33:12        125
   4     72        2018-05-15 16:39:00        156
   5     72        2018-05-15 16:39:41        135
   6     73        2018-05-15 16:39:00        129

现在,我想获取所有具有相同created_dt的记录,直到几分钟。我在下面尝试过,但没有得到合适的结果。

  SELECT question_id, COUNT(Created_dt)
  FROM  TABLE
  GROUP BY Created_dt, question_id
  ORDER BY Created_dt

1 个答案:

答案 0 :(得分:0)

如果我了解您的要求,则可以忽略此查询的秒数。因此,转换为varchar并截短秒数,然后再转换回datetime将完成此操作。也许并不是最好的性能,如果性能是一个问题,您要考虑正确存储datetime而不用秒。

declare @Table table (id int, question_id int, created_dt datetime, secondary_question_id int)

insert into @Table (id, question_id, created_dt, secondary_question_id)
  select 1, 71, '2016-03-12 16:33:00', 123
  union all
  select 2, 71, '2016-03-12 16:33:09', 124
  union all
  select 3, 71, '2016-03-12 16:33:12', 125
  union all
  select 4, 72, '2018-05-15 16:39:00', 156
  union all
  select 5, 72, '2018-05-15 16:39:41', 135
  union all
  select 6, 73, '2018-05-15 16:39:00', 129

--select *, convert(datetime,convert(varchar(17),created_dt,113))
--from @Table

SELECT question_id, COUNT(*)
FROM (
  select question_id, convert(datetime,convert(varchar(17),created_dt,113)) created_dt_new
  from @TABLE
) X
GROUP BY created_dt_new, question_id
ORDER BY created_dt_new