2010-06-09 92 views
1

這可能很容易,但沒有迴避。 SQL Server2005中 我想顯示前100,但如果沒有100只希望顯示這些並沒有包括在結果前10名除非計數爲零

SELECT TOP (100) UserName, FullName_Company, FullName, 
         (SELECT COUNT(*) 
         FROM   dbo.Member_Ref 
         WHERE  (RefFrom_UserName = dbo.view_Members.UserName) AND (RefDate >= '5/1/2010') AND (RefDate <= '6/1/2010')) 
        AS RefFromCount   
FROM   dbo.view_Members 
WHERE (MemberStatus = N'Active') 
ORDER BY RefFromCount DESC 

我一直在使用GROUP BY和HAVING COUNT試過零個計數(*)> 0都具有相同的錯誤結果

回答

1

我加入一個子查詢與數量,並在部分地方被我過濾量> 0

SELECT TOP (100) UserName, FullName_Company, FullName, Quantity AS RefFromCount   
FROM   dbo.view_Members 
JOIN (
    SELECT RefFrom_UserName, COUNT(*) as Quantity 
    FROM   dbo.Member_Ref 
    WHERE  (RefDate >= '5/1/2010') AND (RefDate <= '6/1/2010') 
    GROUP BY RefFrom_UserName 
) as Q on Q.RefFrom_UserName = dbo.view_Members.UserName 
WHERE (MemberStatus = N'Active') 
AND Quantity > 0 
ORDER BY RefFromCount DESC 
+0

這樣做,非常感謝你 – datatoo 2010-06-09 02:09:32

3

考慮:在內部查詢

SELECT TOP (100) UserName, FullName_Company, FullName, 
         (SELECT COUNT(*) 
         FROM   dbo.Member_Ref 
         WHERE  (RefFrom_UserName = dbo.view_Members.UserName) 
          AND (RefDate >= '5/1/2010') AND (RefDate <= '6/1/2010')) 
         HAVING COUNT(*) > 0 
        AS RefFromCount   
FROM   dbo.view_Members 
WHERE (MemberStatus = N'Active') 
ORDER BY RefFromCount DESC 

添加的HAVING條款本身將切出的結果與0計數。

+0

謝謝,我試過了,它仍然返回100個項目,但RefFromCount爲NULL,表示先前顯示爲0的列表的餘額。我想如果有100個,則顯示100個項目,或者如果全部存在,則只顯示90個項目。 – datatoo 2010-06-09 01:54:19

+0

HAVING COUNT(*)> 0不會返回NULL,它會顯示並且用戶數爲零? – user347594 2010-06-09 01:56:53

+0

我也期待得到,但這就是我得到的結果 – datatoo 2010-06-09 02:11:36

0

是否SQL Server 2005中有一個像MySQL中的「限制」關鍵字? (如果是這樣,這種任務有一個非常簡單的解決方案)

+0

它有一個TOP運算符 – Madhivanan 2010-06-09 08:23:07