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

后端 未结 10 2095
别跟我提以往
别跟我提以往 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 22:58

    Update:

    Solution below tested for efficiency on a 2M table and takes but 40 ms.

    Plain DISTINCT on an indexed computed column took 9 seconds.

    See this entry in my blog for performance details:

    • SQL Server: efficient DISTINCT on dates

    Unfortunately, SQL Server's optimizer can do neither Oracle's SKIP SCAN nor MySQL's INDEX FOR GROUP-BY.

    It's always Stream Aggregate that takes long.

    You can built a list of possible dates using a recursive CTE and join it with your table:

    WITH    rows AS (
            SELECT  CAST(CAST(CAST(MIN(date) AS FLOAT) AS INTEGER) AS DATETIME) AS mindate, MAX(date) AS maxdate
            FROM    mytable
            UNION ALL
            SELECT  mindate + 1, maxdate
            FROM    rows
            WHERE   mindate < maxdate
            )
    SELECT  mindate
    FROM    rows
    WHERE   EXISTS
            (
            SELECT  NULL
            FROM    mytable
            WHERE   date >= mindate
                    AND date < mindate + 1
            )
    OPTION  (MAXRECURSION 0)
    

    This will be more efficient than Stream Aggregate

提交回复
热议问题