2017-02-10 178 views
1

我有SQL的查詢是多個表的連接,它返回重複的行和經歷無法找出小時後在那裏它去錯了SQL Server查詢返回重複的行

SELECT 
    StkItem.iUOMStockingUnitID, 
    _etblUnits1.cUnitCode as 'parkSize', 
    _etblUnits2.cUnitCode as 'quantitySize', 
    InvNum.fInvTotExclForeign, 
    [_btblInvoiceLines].*, 
    [_rtblCountry].cCountryName, 
    [CurrencyHist].fBuyRate, 
    Vendor.Name, 
    InvNum.OrderDate, 
    InvNum.InvNumber 
FROM 
    [dbo].[_btblInvoiceLines] 
LEFT JOIN 
    StkItem ON StkItem.StockLink = [_btblInvoiceLines].iStockCodeID 
LEFT JOIN 
    _etblUnits as _etblUnits1 ON _etblUnits1.idunits = StkItem.iUOMDefSellUnitID 
LEFT JOIN 
    _etblUnits as _etblUnits2 ON _etblUnits2.idunits = StkItem.iUOMStockingUnitID 
LEFT JOIN 
    InvNum ON iInvoiceID = AutoIndex 
LEFT JOIN 
    Vendor ON Vendor.DCLink = InvNum.AccountID 
LEFT JOIN 
    [_rtblCountry] ON [_rtblCountry].idCountry = Vendor.iCountryID 
LEFT JOIN 
    [CurrencyHist] ON InvNum.ForeignCurrencyID = [CurrencyHist].iCurrencyID 
WHERE 
    OrderNum = '' 
    AND [CurrencyHist].iCurrencyID = (SELECT TOP 1 iCurrencyID 
             FROM [CurrencyHist] 
             WHERE iCurrencyID = InvNum.ForeignCurrencyID 
             ORDER BY idCurrencyHist DESC) 

這裏是查詢,任何幫助將高度讚賞,在此先感謝

+0

'ORDER BY'在嵌套查詢工作? –

+4

逐個刪除連接,直到額外的行消失。然後你知道問題在哪裏。 –

+0

當我加入currencyhist表 – lulliezy

回答

2

從您以前的意見,當您加入[CurrencyHist]時,問題即將到來。從名字來看,它似乎是歷史表,因此每個貨幣必須有多行作爲歷史記錄。要消除重複的行,您應該加入特定貨幣的最新更新記錄。所以,你的查詢也能像下面,

SELECT StkItem.iUOMStockingUnitID, 
      _etblUnits1.cUnitCode as 'parkSize', 
      _etblUnits2.cUnitCode as 'quantitySize', 
      InvNum.fInvTotExclForeign, 
      [_btblInvoiceLines].*, 
      [_rtblCountry].cCountryName, 
      [CurrencyHist].fBuyRate, 
      Vendor.Name, 
      InvNum.OrderDate, 
      InvNum.InvNumber 
    FROM [dbo].[_btblInvoiceLines] 
    LEFT JOIN StkItem ON StkItem.StockLink = [_btblInvoiceLines].iStockCodeID 
    LEFT JOIN _etblUnits as _etblUnits1 ON _etblUnits1.idunits = StkItem.iUOMDefSellUnitID 
    LEFT JOIN _etblUnits as _etblUnits2 ON _etblUnits2.idunits = StkItem.iUOMStockingUnitID 
    LEFT JOIN InvNum ON iInvoiceID = AutoIndex 
    LEFT JOIN Vendor ON Vendor.DCLink = InvNum.AccountID 
    LEFT JOIN [_rtblCountry] ON [_rtblCountry].idCountry = Vendor.iCountryID 
    LEFT JOIN (SELECT DENSE_RANK() over (partition by [CurrencyHist].iCurrencyID order by [CurrencyHist].LastUpdated desc) as rn,[CurrencyHist].iCurrencyID as 'iCurrencyID' 
    FROM [CurrencyHist] AS [CurrencyHist] 
    )[CurrencyHist] ON InvNum.ForeignCurrencyID = [CurrencyHist].iCurrencyID 
    and [CurrencyHist].rn=1 
WHERE OrderNum = '' AND 
[CurrencyHist].iCurrencyID = (SELECT TOP 1 iCurrencyID 
             FROM [CurrencyHist] 
             WHERE iCurrencyID = InvNum.ForeignCurrencyID 
             ORDER BY idCurrencyHist DESC) 

注:我假設CurrencyHist表中有日期時間數據類型列一個LastUpdated

+0

我剛剛更新了你的建議和工作後,我剛看到這個答案,謝謝 – lulliezy