【问题标题】:Get rows that has same created date datetime till minutes获取具有相同创建日期日期时间的行直到分钟
【发布时间】:2019-10-03 02:26:15
【问题描述】:

我有一个表格,其中包含如下数据:

   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

【问题讨论】:

  • 你能显示预期的结果吗?

标签: sql-server datetime join timestamp


【解决方案1】:

如果我理解您的要求,您想忽略此查询的秒数。因此,转换为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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2021-03-11
    • 2020-03-16
    • 1970-01-01
    相关资源
    最近更新 更多