SQL Server +错误的TOP 1输出

时间:2012-02-22 09:48:54

标签: sql sql-server

我的查询的一部分如下所示,其中TOP 1应该在2条记录中共享,因为有2个网点具有相同的访问次数。显然,查询只返回一条记录。在这种情况下如何显示“准确”输出?

Select TOP 1 (O.Name) as MostVisited
         From [Trans] T 
             INNER JOIN [Outlet] O
             On (T.Outlet_Code = O.Code)

      Where [VoidBy] IS NULL AND [VoidOn] IS NULL AND CardNo In     
            (Select [CardNo] From [Card] Where [CardNo] = 'CARDX' AND [MemberID] = @MemberId)
      Group by O.Name     
      Order by Count(T.Outlet_Code) Desc   

1 个答案:

答案 0 :(得分:10)

Select TOP (1) WITH TIES (O.Name) as MostVisited
       ....

WITH TIES提供“联合顶级”情况。

示例:

DECLARE @t TABLE (foo int, qty int);
INSERt @t VALUES (1, 100), (3, 200), (2, 200);

-- one row, arbitrary
SELECT TOP (1) * FROM @t ORDER BY qty DESC;

-- both rows with "TOP 1 value"
SELECT TOP (1) WITH TIES * FROM @t ORDER BY qty DESC;