mysql - select 一组的最大值 return 其他列的错误值
mysql - select MAX value by a group return wrong values of other column
我想通过 code
和我的数据找到 MAX 值,如下所示:
id
date
code
price
74
2022-01-04
B
64
91
2022-01-07
A
174
112
2022-01-11
B
128
245
2022-01-12
C
841
550
2022-01-14
A
79
780
2022-01-20
B
55
821
2022-01-23
D
45
868
2022-01-28
C
50
890
2022-02-02
B
467
891
2022-02-03
D
58
892
2022-02-04
A
472
如我所料,它将 return 如下所示:
id
date
code
price
245
2022-01-12
C
841
890
2022-02-02
B
467
891
2022-02-03
D
58
892
2022-02-04
A
472
我正在使用以下查询:
select x.id, x.date, x.code, y.yprice
from data AS x
inner join
(
select id, date, code, MAX(price) AS yprice
from data
group by code
) y
on x.id = y.id AND x.code = y.code
并给我以下结果:
关于结果:
MAX 的值是正确的,但是 id 和 date 是错误的。
有解决查询的想法吗?
谢谢...
SELECT X.ID,X.DATE,X.CODE,X.PRICE
FROM
(
SELECT C.id,C.date,C.code,C.price,
ROW_NUMBER()OVER(PARTITION BY C.code ORDER BY C.Price DESC)XCOL
FROM test AS C
)X WHERE X.XCOL=1
你能试试这个吗
我想通过 code
和我的数据找到 MAX 值,如下所示:
id | date | code | price |
---|---|---|---|
74 | 2022-01-04 | B | 64 |
91 | 2022-01-07 | A | 174 |
112 | 2022-01-11 | B | 128 |
245 | 2022-01-12 | C | 841 |
550 | 2022-01-14 | A | 79 |
780 | 2022-01-20 | B | 55 |
821 | 2022-01-23 | D | 45 |
868 | 2022-01-28 | C | 50 |
890 | 2022-02-02 | B | 467 |
891 | 2022-02-03 | D | 58 |
892 | 2022-02-04 | A | 472 |
如我所料,它将 return 如下所示:
id | date | code | price |
---|---|---|---|
245 | 2022-01-12 | C | 841 |
890 | 2022-02-02 | B | 467 |
891 | 2022-02-03 | D | 58 |
892 | 2022-02-04 | A | 472 |
我正在使用以下查询:
select x.id, x.date, x.code, y.yprice
from data AS x
inner join
(
select id, date, code, MAX(price) AS yprice
from data
group by code
) y
on x.id = y.id AND x.code = y.code
并给我以下结果:
关于结果: MAX 的值是正确的,但是 id 和 date 是错误的。
有解决查询的想法吗?
谢谢...
SELECT X.ID,X.DATE,X.CODE,X.PRICE
FROM
(
SELECT C.id,C.date,C.code,C.price,
ROW_NUMBER()OVER(PARTITION BY C.code ORDER BY C.Price DESC)XCOL
FROM test AS C
)X WHERE X.XCOL=1
你能试试这个吗