SQL Server: GROUP BY datetime without ticks
I have a query, that returns all entries, with unique datetime with ticks:
select t.date, count(*) as Count from table t group by t.date having count(*) = 1
I need a query that will return entries with unique datetime without ticks. To get datetime without ticks I'm using:
select CONVERT(VARCHAR(19), t.date, 120), count(*) as Count from table t
So I'm expecting to use query:
select CONVERT(VARCHAR(19), t.date, 120), count(*) as Count from table t group by CONVERT(VARCHAR(19), t.date, 120) having count(*) = 1
But it throws an error:
Column "table.date" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
Do you have any idea what query should I use?
Answers
This works fine:
select convert(varchar(19), t.date, 120), count(*) as count from table t group by convert(varchar(19), t.date, 120) having count(*) = 1 order by convert(varchar(19), t.date, 120)
There are multiple possible datetime values in each group so instead of
ORDER BY t.date
you could use, for example
ORDER BY MIN(t.date)
to avoid this error.