I've read that one good reason to use a CTE is to as Microsoft says:
Enable grouping by a column that is derived from a scalar sub-select, or a function that is either not deterministic or has external access.
So I tried this example using SQL 2014 and Adventure Works 2012 DB and it worked!
SELECT DateDiff(D,H.OrderDate,GETDATE()), Count(*)
FROM Sales.SalesOrderHeader H
GROUP BY DateDiff(D,H.OrderDate,GETDATE())
ORDER BY DateDiff(D,H.OrderDate,GETDATE())
Which doesn't seem right, as GETDATE()
is a not deterministic!
So really two questions:
- Any one know why this example works, it seems it shouldn't.
- Does anyone have a good example of a similar query where a CTE helps
overcome the "group by non-determnistic function" limitation?
Thanks!