2016-11-17 87 views
-1

我只想顯示每個ID的記錄少於10個條目的ID,一個ID可能有幾個值,如下面的數據中所示。我想 我已經嘗試此查詢,但它也選擇了記錄ID 2選擇少於10個條目的記錄sql server

select ID, Name ,LastName ,PaymentDate,POSITION 
    From (select ID, Name ,LastName ,PaymentDate ,ROW_NUMBER() OVER(PARTITION BY ID ORDER BY PaymentDate DESC) AS POSITION 

    ) 
    where Position < 10 

任何幫助,請

ID Name LastName PaymentDate 
    1 John Abraham 2015-05-08 
    1 John Abraham 2014-05-08 
    1 John Abraham 2013-05-08 
    1 John Abraham 2012-05-08 
    1 John Abraham 2011-05-08 
    1 John Abraham 2010-05-08 
    ------------------------------ 
    2 Adam White 2015-05-08 
    2 Adam White 2014-05-08 
    2 Adam White 2013-05-08 
    2 Adam White 2012-05-08 
    2 Adam White 2011-05-08 
    2 Adam White 2010-05-08 
    2 Adam White 2009-05-08 
    2 Adam White 2008-05-08 
    2 Adam White 2007-05-08 
    2 Adam White 2006-05-08 
    2 Adam White 2005-05-08 
    2 Adam White 20004-05-08 

回答

1

請嘗試:

Select ID, Name, LastName, PaymentDate 
    From MyTable 
Where ID in (Select ID From MyTable Group By ID Having Count(*) < 10); 
+0

非常感謝,如預期般運作良好。我已經完成了這個查詢,子查詢中有一點錯誤。 – Ilyas

2
SELECT ID, COUNT(ID) 
FROM sometable 
GROUP BY ID 
HAVING COUNT(ID) < 10 
2

你想count(*),不row_number()

select ID, Name, LastName, PaymentDate 
from (select ID, Name, LastName, PaymentDate, 
      count(*) over (partition by ID) as cnt 
     from . . . 
    ) t 
where cnt < 10; 

這顯示行(你的問題建議是你想要的)。如果你只想要的ID,然後聚集更好:

select id 
from t 
group by id 
having count(*) < 10; 
+0

感謝戈登,但它不能正常工作,它確實有效的子查詢,如下。 – Ilyas

+0

@Ilyas。 。 。你是什​​麼意思「它不工作」?這些應該做你所要求的。 –

+0

我試過了你的查詢,但它沒有給我預期的結果。該查詢還會顯示一些ID,其中有更多10個條目 – Ilyas

相關問題