Group by datetime ignoring time portion

前端 未结 2 1109
鱼传尺愫
鱼传尺愫 2021-01-06 02:32

Is it possible to write a Microsoft SQL query that will group by a datetime data-type but ignoring the time part such as the hour and minute?

2条回答
  •  不知归路
    2021-01-06 02:41

    If you have a large table and want grouping to happen fast, you cannot rely grouping on an expression.

    Create an additional datetime column on your table and have it filled by a trigger that calculates the base date from you "real" date:

    UPDATE
      MyTable
    SET
      EffectiveDate = DATEADD(DAY, 0, DATEDIFF(DAY, 0, t.RecordDate))
    FROM
      MyTable t
      INNER JOIN inserted i ON i.RowID = t.RowID
    

    Then put an index on EffectiveDate and grouping (and searching) will be a lot faster.

提交回复
热议问题