SQL更新组中具有最小值的列

时间:2012-10-19 20:29:16

标签: sql oracle

我正在尝试使用DESC组中的最小值更新MD_ID列 例如,我希望DESC =语言的所有行都得到MD_ID = 21,即min(21,163,287)= 21。为简化起见,始终是与SOURCE = 1相关联的MD_ID。

数据如下所示:

MD_ID|SOURCE|DESC           |MSG |SEGMNT|FIELD
  21 |1     |Language       |A11 |PID   |33
 163 |2     |Language       |A11 |PID   |33
 287 |3     |Language       |A11 |PID   |33
  22 |1     |Sex            |B22 |MSH   |8
 145 |2     |Sex            |B22 |MSH   |8
 171 |3     |Sex            |B22 |MSH   |8
  23 |1     |Marital Status |C33 |NK1   |16
 145 |2     |Marital Status |C33 |NK1   |16
 289 |3     |Marital Status |C33 |NK1   |1
  24 |1     |Religion       |D44 |GT1   |7
 167 |2     |Religion       |D44 |GT1   |7
 292 |3     |Religion       |D44 |GT1   |7

我需要它看起来像这样:

MD_ID|SOURCE|DESC           |MSG |SEGMNT|FIELD
  21 |1     |Language       |A11 |PID   |33
  21 |2     |Language       |A11 |PID   |33
  21 |3     |Language       |A11 |PID   |33
  22 |1     |Sex            |B22 |MSH   |8
  22 |2     |Sex            |B22 |MSH   |8
  22 |3     |Sex            |B22 |MSH   |8
  23 |1     |Marital Status |C33 |NK1   |16
  23 |2     |Marital Status |C33 |NK1   |16
  23 |3     |Marital Status |C33 |NK1   |1
  24 |1     |Religion       |D44 |GT1   |7
  24 |2     |Religion       |D44 |GT1   |7
  24 |3     |Religion       |D44 |GT1   |7

1 个答案:

答案 0 :(得分:4)

UPDATE YourTable t
    SET MD_ID = (SELECT MD_ID
                     FROM YourTable t2
                     WHERE t2.DESC = t.DESC
                         AND t2.SOURCE = 1)