Select max value of each group
在æ到的问题ä¸ï¼Œæœ‰ä¸€ä¸ªè§£å†³æ–¹æ¡ˆå¯ä»¥èŽ·å–æ¯ä¸ªç»„的最大值。我需è¦æ›´å¤šå¸®åŠ©ï¼Œæˆ‘希望æ¯ä¸ªç»„的最大值以åŠè¯¥æœ€å¤§å€¼çš„å¦ä¸€åˆ—(有问题的第三列)。桌å看起æ¥åƒè¿™æ ·
Name Value AnotherColumn
Pump1 1000 1
Pump1 2000 2
Pump2 1000 2
Pump2 2000 1
输出应为
Name Value AnotherColumn
Pump1 2000 2
Pump2 2000 1
我æ£åœ¨ä½¿ç”¨Microsoft Sql Server2012。å¦ä¸€åˆ—å¯ä»¥æ˜¯ä»»ä½•ç±»åž‹ï¼Œå®ƒä¸é™äºŽæ•´æ•°ï¼Œæˆ‘åªæƒ³èŽ·å–å¦ä¸€åˆ—以获å–æ¯ä¸ªç»„的最大值。
ç”案 0 :(得分:1)
使用row_number()函数:
select * from
(select *, row_number() over (partition by name order by value desc) as rn)a
where rn=1
ç”案 1 :(得分:1)
一个选项使用ROW_NUMBER
:
SELECT Name, Value, AnotherColumn
FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Value DESC) rn
FROM yourTable
) t
WHERE rn = 1
请注æ„,如果您希望æ¯ä¸ªå称的所有è”系都具有最大价值,则å¯ä»¥å°†ROW_NUMBER
替æ¢ä¸ºRANK
(或者也许是DENSE_RANK
),以获å–所有è”系。
ç”案 2 :(得分:0)
åªéœ€ä½¿ç”¨group by
å’Œmax()
select name ,max(value), max(AnotherColumn)
from t group by Name
您å¯ä»¥ä½¿ç”¨ç›¸å…³çš„å查询
select * from t t1
where t1.value in (select max(t2.value) from t t2 where t1.name=t2.name)
ç”案 3 :(得分:0)
您å¯ä»¥å°è¯•åœ¨where
ä¸ä½¿ç”¨å查询æ¥è¿›è¡Œåˆ›å»ºã€‚
SELECT *
FROM T t1
WHERE Value = (
SELECT MAX(Value)
FROM T tt
WHERE tt.Name = t1.Name
)