SQL最近更新的行

时间:2017-08-29 14:45:14

标签: sql

我从SQL数据库中提取信息,但由于多次更新,它会多次显示所有行。 我已设法使用distinct函数消除重复,但仍然显示多行更改。

即。

原始数量= 4
更新1数量= 5
更新2数量= 6

我想要的是每一行的最新更新,列 OLLNID

SELECT DISTINCT  
    OLMCU,
    OLKCOO,
    OLDOCO,
    OLDCTO,
    Date( OLTRDJ, CYYDDD ) AS OLTRDJ,
    OLLNID AS OLLNID_1, 
    OLDSC1,
    OLDSC2 AS OLDSC2_1,
    OLUOM,
    OLUORG,
    OLPRRC,
    OLAEXP,
    OLANBY 
FROM 
    E1PDES01.PRODDTA.F43199 F43199 
WHERE 
    OLMCU = '13248'
    AND Date( OLTRDJ, CYYDDD ) >= '01/01/2017'
    AND OLDCTO = 'OP'
    AND OLDOCO = 13484379 
ORDER BY 
    6

2 个答案:

答案 0 :(得分:0)

取决于你使用的SQL Flavor这可能不起作用,我对你的数据做了一些疯狂的假设,所以如果你可以提供更多信息(可能是模式/类型,SQL Flavor,可能是两个或三个虚拟行)我会编辑我的答案

 SELECT   
    org.OLMCU,
    org.OLKCOO,
    org.OLDOCO,
    org.OLDCTO,
    Date(org.OLTRDJ, CYYDDD ) AS OLTRDJ,
    org.OLLNID AS OLLNID_1, 
    org.OLDSC1,
    org.OLDSC2 AS OLDSC2_1,
    org.OLUOM,
    org.OLUORG,
    org.OLPRRC,
    org.OLAEXP,
    org.OLANBY 
FROM 
    E1PDES01.PRODDTA.F43199 F43199 as org
LEFT OUTER JOIN E1PDES01.PRODDTA.F43199 F43199 aux ON org.OLLNID = aux.OLLNID AND org.OLLNID < aux.OLLNID
WHERE 
    org.OLMCU = '13248'
    AND Date( org.OLTRDJ, CYYDDD ) >= '01/01/2017'
    AND org.OLDCTO = 'OP'
    AND org.OLDOCO = 13484379 
    AND aux.OLLNID IS NULL
GROUP BY 
    org.OLMCU,
    org.OLKCOO,
    org.OLDOCO,
    org.OLDCTO,
    Date(org.OLTRDJ, CYYDDD ) AS OLTRDJ,
    org.OLLNID AS OLLNID_1, 
    org.OLDSC1,
    org.OLDSC2 AS OLDSC2_1,
    org.OLUOM,
    org.OLUORG,
    org.OLPRRC,
    org.OLAEXP,
    org.OLANBY 
ORDER BY org.OLLNID

答案 1 :(得分:0)

像subkonstrukt一样,我猜你真正想要的是什么。 如果您想要OLLNID的最新结果(例如日期),那么您可以按所有其他值进行分组(当它们不同时)并选择最大OLLNID。

SELECT
    OLMCU,
    OLKCOO,
    OLDOCO,
    OLDCTO,
    Date(OLTRDJ, CYYDDD) AS OLTRDJ,
    MAX(OLLNID) AS OLLNID_1,
    OLDSC1,
    OLDSC2 AS OLDSC2_1,
    OLUOM,
    OLUORG,
    OLPRRC,
    OLAEXP,
    OLANBY
FROM E1PDES01.PRODDTA.F43199 F43199
WHERE OLMCU = '13248'
      AND Date(OLTRDJ, CYYDDD) >= '01/01/2017'
      AND OLDCTO = 'OP'
      AND OLDOCO = 13484379
GROUP BY
    OLMCU,
    OLKCOO,
    OLDOCO,
    OLDCTO,
    OLTRDJ,
    OLDSC1,
    OLDSC2,
    OLUOM,
    OLUORG,
    OLPRRC,
    OLAEXP,
    OLANBY;