How to quickly select DISTINCT dates from a Date/Time field, SQL Server

后端 未结 10 2115
别跟我提以往
别跟我提以往 2021-01-31 22:42

I am wondering if there is a good-performing query to select distinct dates (ignoring times) from a table with a datetime field in SQL Server.

My problem isn\'t getting

10条回答
  •  悲哀的现实
    2021-01-31 23:01

    If you want to avoid the step extraction or reformatting the date - which is presumably the main cause of the delay (by forcing a full table scan) - you've no alternative but to store the date only part of the datetime, which unfortunately will require an alteration to the database structure.

    If your using SQL Server 2005 or later then a persisted computed field is the way to go

    Unless otherwise specified, computed columns are virtual columns that are
    not physically stored in the table. Their values are recalculated every 
    time they are referenced in a query. The Database Engine uses the PERSISTED 
    keyword in the CREATE TABLE and ALTER TABLE statements to physically store 
    computed columns in the table. Their values are updated when any columns 
    that are part of their calculation change. By marking a computed column as 
    PERSISTED, you can create an index on a computed column that is deterministic
    but not precise. 
    

提交回复
热议问题