如何查询差异重复数据

时间:2016-06-22 04:34:53

标签: sql ms-access

SQL

我有数据

BOMcat | BOM  | AltBOM | Counter |   ChangeNo   | DeID | DID | PreCounter | Baseqty
M      | 7882 | A      |      26 | GUC320140101 |  X   |     |            |100.000
M      | 7882 | B      |       1 | GUC320140101 |  X   |     |            |100.500
M      | 7882 | B      |     307 | GUC320141225 |  X   |     |  1         |100.500
M      | 9772 | 01     |     600 | GUC120140904 |  X   |     |  397       |116.188
M      | 9772 | 01     |     601 | GUC120150504 |  X   |     |  600       |116.488
M      | 9772 | 01     |    1021 | GUC120150703 |  X   |     | 601        |116.488

我想选择1 BOM/1 AltBOM条件是最后选择ChangeNo

  • PreCounter:意味着此行已更改EX行。 PreCounter 1此行已更改BOMCounter 1
  • ' Changeno':Structrue是GUCXYYYYMMDD
               - X:运行号码
               - YYYY:年份            - MM:月份            - DD:日期

预期结果

M   |   7882 |  A    |     26  | GUC320140101 | X |  |      | 100.000
M   |   7882 |  B    |    307  | GUC320141225 | X |  |  1   | 100.500
M   |   9772 |  01   |   1021  | GUC120150703 | X |  |  601 | 116.488

2 个答案:

答案 0 :(得分:0)

最简单的方法是使用NOT EXISTS返回一行,如果没有其他行具有相同的BOM / AltBOM且具有更高的ChangeNo:

select *
from tablename t1
where not exists (select * from tablename t2
                  where t2.BOM = t1.BOM
                    and t2.AltBOM = t1.AltBOM
                    and t2.ChangeNo > t1.ChangeNo)

或者,使用join

进行自我group by
select t1.*
from tablename t1
    join (select BOM, AltBOM, MAX(ChangeNo) as ChangeNo
          from tablename
          group by BOM, AltBOM) t2
    on t1.BOM = t2.BOM and t1.AltBOM = t2.AltBOM and t1.ChangeNo = t2.ChangeNo

答案 1 :(得分:0)

在MS Access中,我会使用ng-init='function a() {}' 子句中的相关子查询执行此操作:

where