在一个特定列中折叠具有相等值的行

时间:2016-08-04 14:36:33

标签: mysql sql sql-server sql-server-2008

我有一张表格,里面写着交易数据。我需要在加入其他表时查询所述交易,但d.originalorderid不是唯一的条目,我得到几个重复的条目。我想:

  1. 为每个唯一的d.originalorderid选择一行
  2. 此行应为最新(最大ID)
  3. 我该怎么做?这是我现在的查询。

    SELECT  d.id, 
            d.date, 
            d.ip, d.panmask, 
            d.merchantorderid, 
            d.amount, 
            d.cardholder, 
            d.bankhumanname,
            d.cardtypeid, 
            d.bankcountrycode, 
            d.usercountrycode,
            mc.paymentkey as merchantname, 
            dt.status, 
            d.merchantcontract,
            dt.tag, 
            d.originalorderid, 
            ds.refnumber, 
            ds.dealauthcode, 
            mc.processingid, 
            pc.Name as processing, 
            d.customparams       
    FROM Deal as d 
    LEFT JOIN MerchantContract as mc ON mc.Id = d.MerchantContract 
    LEFT JOIN DealTrace as dt ON d.Id = dt.DealId 
       AND dt.id = (SELECT MAX(id) 
                    FROM DealTrace WITH (nolock) 
                    WHERE DealId = d.id) 
    LEFT JOIN DealSummary ds ON d.Id = ds.DealId 
       AND ds.id = (SELECT MAX(id) 
                    FROM DealSummary WITH (nolock) 
                    WHERE DealId = d.id) 
    LEFT JOIN Processing pc on mc.ProcessingId = pc.id 
    WHERE (d.MerchantContract IN ('12')) 
    ORDER BY ID desc OFFSET 0 ROWS FETCH NEXT 1000 ROWS ONLY
    

1 个答案:

答案 0 :(得分:0)

如果我理解了该要求,而不是加入Deal表,则加入到其上的相关子查询,该子查询返回具有相同原始订单ID的最高交易ID的交易。测试它,但我认为它确定..

SELECT ....
FROM
(SELECT *
FROM Deal d1
WHERE d1.Id=(SELECT MAX(Id)
                         FROM Deal d2
                         WHERE d2.OriginalOrderId=d1.OriginalOrderId)) d
LEFT JOIN MerchantContract as mc ON mc.Id = d.MerchantContract 
 etc etc