2008-09-19 62 views

回答

5
select dates 
    from table t 
group by dates having count(dates) < k ; 

希望它適用於ORACLE。 HTH

8
SELECT * FROM [MyTable] WHERE [Date] IN 
(
    SELECT [Date] 
    FROM [MyTable] 
    GROUP By [Date] 
    HAVING COUNT(*) < @Max 
) 

請參閱@ [SQLMenace]的迴應。這與此非常相似,但根據數據庫的不同,假設優化器沒有實質性改變,他的JOIN運行速度可能會更快。

3

使用COUNT聚合:

SELECT Date 
FROM SomeTable 
GROUP BY Date 
HAVING COUNT(*) < @k 
2

對於 「出現x次」 查詢時最好使用HAVING子句。在你的情況,查詢可以像:

SELECT Date FROM table GROUP BY Date HAVING COUNT(*)<k 

,或者在您需要選擇不同的日期等欄目:

SELECT * FROM Table WHERE Date IN (
SELECT Date FROM table GROUP BY Date HAVING COUNT(*)<k) 

您也可以重寫IN到INNER JOIN,但是這不會提高性能,因爲實際上,查詢優化器將在大多數RDBMS中爲您執行此操作。具有日期索引肯定會提高此查詢的性能。

1
SELECT date, COUNT(date) 
FROM table 
GROUP BY date 
HAVING COUNT(date) < k 

然後來獲得原始數據傳回:

SELECT table.* 
FROM table 
INNER JOIN (
    SELECT date, COUNT(date) 
    FROM table 
    GROUP BY date 
    HAVING COUNT(date) < k) dates ON table.date = dates.date 
1

假設你使用的是Oracle,而k = 5: -

select date_col,count(*) 
from your_table 
group by date_col 
having count(*) < 5; 

如果你的約會專欄時間填寫並且您希望忽略它,請修改查詢,使其看起來如下所示: -

select trunc(date_col) as date_col,count(*) 
from your_table 
group by trunc(date_col) 
having count(*) < 5; 
2

例如

DECLARE @Max int 
SELECT @Max = 5 

SELECT t1.* 
FROM [MyTable] t1 
JOIN(
    SELECT [Date] 
    FROM [MyTable] 
    GROUP By [Date] 
    HAVING COUNT(*) < @Max 
) t2 on t1.[Date] = t2.[Date] 
+0

upvote因爲連接可能比我的IN()子句更快 – 2008-09-19 20:05:08

0

您可能無法直接檢測DateField來算,如果你的日期包括倍。您可能需要首先轉換爲年/月/日格式,然後再進行計數。

否則您的計數將會關閉,因爲通常只有極少數記錄具有完全相同的時間。