簡體   English   中英

獲取SQL Server中具有Max值的行

[英]Fetch the row which has the Max value for a column in SQL Server

我發現了一個與此問題非常相似的問題,但使用了Oracle獨有的功能。 我希望在SQL Server中執行此操作。

我有這樣一張桌子:

MyTable
--------------------
MyTableID  INT  PK
UserID     INT
Counter    INT

每個用戶可以有多行,每行的Counter值不同。 我需要為每個用戶找到具有最高Counter值的行。

我該如何在SQL Server 2005中執行此操作?

我能想到的最好的是一個查詢返回每個UserIDMAX(Counter) ,但我需要整行,因為為了簡單起見,我的表定義中沒有顯示此表中的其他數據。

編輯:我從這篇文章的一些答案中引起了我的注意,我忘記了一個重要的細節。 可以有2+行,其中UserID可以具有相同的MAX計數器值。 下面的示例更新了預期的數據/輸出應該是什么。

有了這些數據:

MyTableID   UserID   Counter
---------   -------  --------
1           1         4
2           1         7
3           4         3
4           11        9
5           11        3
6           4         6
...
9           11        9

我想要重復MAX值的這些結果,選擇SQL Server選擇它們的任何順序的第一次出現。 在這種情況下返回哪些行並不重要,只要UserID / Counter對是不同的:

MyTableID   UserID    Counter
---------   -------   --------
2           1         7
4           11        9
6           4         6

我喜歡在這種情況下使用公用表表達式,其中包含一個合適的ROW_NUMBER()函數:

WITH MaxPerUser AS
(
  SELECT 
    MyTableID, UserID, Counter,
    ROW_NUMBER() OVER(PARTITION BY userid ORDER BY Counter DESC) AS 'RowNumber'
  FROM dbo.MyTable
)
SELECT MyTableID, UserID, Counter 
FROM MaxPerUser
WHERE RowNumber = 1

通過UserID對數據進行分區,按每個用戶的Counter(降序)對其進行排序,然后為每個用戶標記以1開頭的每一行。 只選擇rownumber為1的那些行,並且你有最大值。 每個用戶的價值。

就這么簡單:-)我得到的結果是這樣的:

MyTableID   UserID  Counter  
   2           1        7   
   6           4        6
   4          11        9

每個用戶只有一個條目,無論每個用戶有多少行具有相同的最大值。

我想這會對你有所幫助。

SELECT distinct(a.userid), MAX(a.counterid) as counterid 
FROM    mytable a INNER JOIN mytable b ON a.mytableid = b.mytableid 
GROUP BY a.userid

有幾種方法可以做到這一點,看看這包括一個聚合列的相關值顯示了幾種方法,包括性能差異

這是一個例子

select t1.*
from(
select UserID, max(counter) as MaxCount
from MyTable
group by UserID) t2
join MyTable t1 on t2.UserID =t1.UserID
and t1.counter = t2.counter
select m.* 
from MyTable m
inner join (
    select UserID, max(Counter) as MaxCounter
    from MyTable
    group by UserID
) mm on m.UserID = mm.UserID and m.Counter = mm.MaxCounter

試試這個......我很確定這是真正確保每個用戶獲得一行的唯一方法。

SELECT MT.* 
FROM    MyTable MT
    INNER JOIN (
        SELECT  MAX(MID.MyTableId) AS MaxMyTableId,
            MID.UserId
        FROM    MyTable MID
            INNER JOIN (
                SELECT  MAX(Counter) AS MaxCounter, UserId
                FROM    MyTable
                GROUP BY UserId
            ) AS MC
                ON (MID.UserId = MC.UserId
                    AND MID.Counter = MC.MaxCounter)
        GROUP BY MID.UserId
    ) AS MID
        ON (MID.UserId = MC.UserId
            AND MID.MyTableId = MC.MaxMyTableId)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM