简体   繁体   English

SQL Server:GROUP BY日期时间,没有刻度

[英]SQL Server: GROUP BY datetime without ticks

I have a query, that returns all entries, with unique datetime with ticks: 我有一个查询,该查询返回所有条目,带有带有刻度的唯一datetime

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. 我需要一个查询,该查询将返回具有唯一datetime没有刻度的条目。 To get datetime without ticks I'm using: 要获取没有滴答声的datetime ,我正在使用:

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. ORDER BY子句中的“ table.date”列无效,因为它既不包含在聚合函数中也不在GROUP BY子句中。

Do you have any idea what query should I use? 您知道我应该使用什么查询吗?

There are multiple possible datetime values in each group so instead of 每个组中有多个可能的datetime值,因此代替

ORDER BY t.date

you could use, for example 您可以使用,例如

ORDER BY MIN(t.date)

to avoid this error. 以避免此错误。

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) 

You have to ORDER BY an expression in the GROUP BY or an aggregation 您必须在GROUP BY中的表达式或聚合中进行ORDER BY

ORDER BY
   CONVERT(VARCHAR(19), date, 120)

example: 例:

SELECT
   ShorterDateTime, COUNT(*)
FROM
    (
    select CONVERT(VARCHAR(19), date, 120) AS ShorterDateTime
    from table
    ) t
GROUP BY
   ShorterDateTime
HAVING
   COUNT(*) > 1
ORDER BY
   ShorterDateTime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM