0

我有一张如下表

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 中做到这一点?

4

4 回答 4

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 |

看到这个 SQLFiddle

于 2012-11-22T07:23:26.143 回答
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

是一个 sqlfiddle 演示

于 2012-11-22T08:26:38.807 回答
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;
于 2012-11-22T07:28:28.517 回答
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
于 2012-11-22T07:53:01.163 回答