I have this SQL query:
SELECT COUNT(DISTINCT CustomerName) over(
ORDER BY OrderTimestamp
RANGE BETWEEN INTERVAL 2 hour PRECEDING AND CURRENT ROW
) AS count_per_time
FROM Orders
WHERE CustomerName IS NOT null
AND CustomerName != ''
but it doesn’t work because DISTINCT is not allowed with OVER clause. Could anyone help me how to solve it, please? Thank you very much.
2
Answers
You can try using
DENSE_RANK()
, withPARTITION BY
the grouped columns, andORDER BY
bothASC
andDESC
on the columns to count:I don’t think that this can be solved with window functions.
There is an emulation technique that uses a substraction of
dense_rank
s, but the latter does not support window frame specifications (ie: therange
/rows
syntax in your original code). Well, to be precise, it actually allows the syntax, but silently ignores it : so it still operates over the whole partition. This is explained in the documentation:It seems like the only option left is a subquery: