我有一张如下表格
ID M1 M2 M3 M4 M5
121 3 5 6 8 4
122 5 2 1 9 6
对于每一行,我需要获得具有最大值的三列,其他值应为NULL。对于上表,输出应为:
ID M1 M2 M3 M4 M5
121 5 6 8
122 5 9 6
任何人都可以帮我在Oracle或MySQL中如何做到这一点吗?
答案 0 :(得分:1)
如果您想从表中获取最大值,可以使用以下子查询:
SELECT ID
,(CASE WHEN M1 = MM1 THEN M1 ELSE '' END) AS M1
,(CASE WHEN M2 = MM2 THEN M2 ELSE '' END) AS M2
,(CASE WHEN M3 = MM3 THEN M3 ELSE '' END) AS M3
,(CASE WHEN M4 = MM4 THEN M4 ELSE '' END) AS M4
,(CASE WHEN M5 = MM5 THEN M5 ELSE '' END) AS M5
FROM Table1
JOIN
(
SELECT MAX(M1) AS MM1
,MAX(M2) AS MM2
,MAX(M3) AS MM3
,MAX(M4) AS MM4
,MAX(M5) AS MM5
FROM Table1
) A
输出:
| ID | M1 | M2 | M3 | M4 | M5 |
--------------------------------
| 121 | | 5 | 6 | | |
| 122 | 5 | | | 9 | 6 |
答案 1 :(得分:1)
试试这个(aaabbb是我在小提琴中给你的桌子的名字):
with p as (
select *
from aaabbb
unpivot
(
v for c in (m1,m2,m3,m4,m5)
)
), max_v as (
select p1.id, max(p1.v) v1, max(p2.v) v2, max(p3.v) v3
from p p1
join p p2 on p1.v > p2.v and p1.id = p2.id
join p p3 on p2.v > p3.v and p2.id = p3.id
group by p1.id)
select ab.id,
case when m1 in (mv.v1, mv.v2, mv.v3) then m1 end m1,
case when m2 in (mv.v1, mv.v2, mv.v3) then m2 end m2,
case when m3 in (mv.v1, mv.v2, mv.v3) then m3 end m3,
case when m4 in (mv.v1, mv.v2, mv.v3) then m4 end m4,
case when m5 in (mv.v1, mv.v2, mv.v3) then m5 end m5
from aaabbb ab join max_v mv on ab.id = mv.id
结果是:
ID M1 M2 M3 M4 M5
121 5 6 8
122 5 9 6
Here是一个sqlfiddle演示
答案 2 :(得分:0)
在oracle :: 我不确定你试图在这里调用的某个规则:
select id,
decode(m1,1,null,2,null,3,null,4,null,M1) M1,
decode(m2,1,null,2,null,3,null,4,null,M2) M2,
decode(m3,1,null,2,null,3,null,4,null,M3) M3,
decode(m4,1,null,2,null,3,null,4,null,M4) M4,
decode(m5,1,null,2,null,3,null,4,null,M5) M5
from tab order by id;
答案 3 :(得分:0)
尝试此查询 -
SELECT
id,
IF(t1.m1 = t2.m1, t1.m1, null) m1,
IF(t1.m2 = t2.m2, t1.m2, null) m2,
IF(t1.m3 = t2.m3, t1.m3, null) m3,
IF(t1.m4 = t2.m4, t1.m4, null) m4,
IF(t1.m5 = t2.m5, t1.m5, null) m5
FROM
m_table t1,
(SELECT
MAX(m1) m1, MAX(m2) m2, MAX(m3) m3, MAX(m4) m4, MAX(m5) m5 FROM m_table
) t2