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
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:
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