2011-11-30 61 views
2

我有一個查詢,返回所有條目,具有獨特的datetime蜱:SQL服務器:GROUP BY日期時間無蜱

select t.date, count(*) as Count 
    from table t 
    group by t.date having count(*) = 1 

我需要一個查詢將返回獨特datetime條目沒有蜱。爲了得到datetime無蜱我使用:

select CONVERT(VARCHAR(19), t.date, 120), count(*) as Count 
from table t 

所以我希望使用查詢:

select CONVERT(VARCHAR(19), t.date, 120), count(*) as Count 
    from table t 
    group by CONVERT(VARCHAR(19), t.date, 120) having count(*) = 1 

但它拋出一個錯誤:

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.

你有什麼我應該使用什麼查詢?

回答

2

這工作得很好:

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) 
3

有每個組中多個可能datetime值,所以不是

ORDER BY t.date 

可以使用,例如

ORDER BY MIN(t.date) 

避免這種錯誤。

+3

當然,'ORDER BY '!他沒有在查詢中包含該子句,我完全錯過了錯誤消息中的引用。絕對同意,+1 –

1

你必須ORDER BY在GROUP BY或表達匯聚

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

例如:

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