[英]How to select a row with maximum value for a column in MySQL?
*沒有其他可用的答案解決了我的問題
我有一張這樣的桌子
id,cc,count
'1','HN','22'
'1','US','18'
'1','VN','1'
'2','DK','2'
'2','US','256'
'3','SK','1'
'3','US','66310'
'4','UA','2'
'4','US','263'
'6','FR','7'
'6','US','84'
'9','BR','3'
我想獲取具有最大計數的ID的行,如下所示:
id,cc,count
'1','HN','22'
'2','US','256'
'3','US','66310'
'4','US','263'
'6','US','84'
'9','BR','3'
我目前的代碼是這樣的,但我沒有得到預期的結果:
SELECT t.* FROM t
JOIN (
SELECT
t.id,t.cc
,max(t.count) as max_slash24_count
FROM t
group by t.id,t.cc
) highest
ON t.count = highest.max_slash24_count
and t.cc = highest.cc
有人可以幫幫我嗎?
從group by
刪除CC
列。 嘗試這個。
SELECT t.* FROM t
JOIN (
SELECT
t.id
,max(t.count) as max_slash24_count
FROM t
group by t.id
) highest
ON t.count = highest.max_slash24_count
and t.id= highest.id
嘗試這個:
create table t (id varchar(10), cc varchar(10), count varchar(10))
insert into t (id,cc,count) values ('1','HN','22');
insert into t (id,cc,count) values ('1','US','18');
insert into t (id,cc,count) values ('1','VN','1');
insert into t (id,cc,count) values ('2','DK','2');
insert into t (id,cc,count) values ('2','US','256');
insert into t (id,cc,count) values ('3','SK','1');
insert into t (id,cc,count) values ('3','US','66310');
insert into t (id,cc,count) values ('4','UA','2');
insert into t (id,cc,count) values ('4','US','263');
insert into t (id,cc,count) values ('6','FR','7');
insert into t (id,cc,count) values ('6','US','84');
insert into t (id,cc,count) values ('9','BR','3');
select *
from t
where exists (
select *
from t as t1
group by t1.id
having t1.id = t.id and max(t1.count) = t.count
)
結果
ID CC COUNT
-------------
1 HN 22
2 US 256
3 US 66310
4 US 263
6 US 84
9 BR 3
這個問題在SO上得到了很多次回答。 查詢就像這樣簡單:
SELECT m.id, m.cc, m.count
FROM t m # "m" from "max"
LEFT JOIN t b # "b" from "bigger"
ON m.id = b.id # match a row in "m" with a row in "b" by `id`
AND m.count < b.count # match only rows from "b" having bigger count
WHERE b.count IS NULL # there is no "bigger" count than "max"
您的問題的真正問題是列類型。 如果count
是char
(而不是int
),則使用字典順序而不是數字順序進行字符串比較。
例如,如果第三行顯示:
'1','VN','123'
您可能希望在輸出中選擇它,因為123
大於22
。 這不會發生,因為,作為字符串, '123'
小於'22'
。
即便如此,這已經得到了解決,使用ROW_NUMBER
功能,因為在SQL Server中非常有趣和有趣:請查看此查詢:
SELECT TT.Id, TT.cc, TT.count
FROM (
SELECT t.cc
, t.count
, @row_number:=CASE WHEN @Id=Id THEN @row_number+1 ELSE 1 END AS row_number
, @Id:=Id AS Id
FROM t, (SELECT @row_number:=0, @Id:='') AS temp
ORDER BY t.Id, t.count DESC
) AS TT
WHERE TT.row_number = 1
ORDER BY TT.Id;
它產生預期的輸出:
| Id | cc | count |
|----|----|-------|
| 1 | HN | 22 |
| 2 | US | 256 |
| 3 | US | 66310 |
| 4 | US | 263 |
| 6 | US | 84 |
| 9 | BR | 3 |
我從@Andrey Morozov那里獲取了測試數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.