如何在没有DISTINCT的情况下删除SQL中的重复项

时间:2017-05-10 19:23:13

标签: ssms

我在下面有这个代码,它会在发票#上重复。

SELECT DISTINCT                     
 APVID [VENDOR ID],                  
 APINV [INVOICE #],
APEXDV [DIVISION],
 APEXLT [STORE #],
APEXAC [GL #],
APSTK# [STOCK #],
 APIDTE [INVOICE DATE],
 APCDTE [PAID DATE],
 APDSC [DESCRIPTION],
 APEX$$ [LINE AMOUNT],
APAMT [INVOICE AMOUNT],
appym [PAID AMOUNT],
APCHK [CHECK #],                          
 APITEM [BARCODE #],
APSEQ [Line item]
FROM  [AccountingDM].[dbo].[tblPpAPInv]               
WHERE APVID in ('DWI006', 'CV2829', 'dw 007', 'dwi001')
and apcdte between 20170101 and 20170331

有没有办法让它只拉一次而不是多次发票?

提前致谢

1 个答案:

答案 0 :(得分:1)

您可以附加FETCH FIRST 1 ROW ONLY&在查询结束时OFFSET仅提取一条记录。根据您是否需要最新或最旧的发票或其他一些条件,您还可以ORDER BY ASC|DESC

SELECT DISTINCT                     
   APVID [VENDOR ID],                  
   APINV [INVOICE #],
   APEXDV [DIVISION],
   APEXLT [STORE #],
   APEXAC [GL #],
   APSTK# [STOCK #],
   APIDTE [INVOICE DATE],
   APCDTE [PAID DATE],
   APDSC [DESCRIPTION],
   APEX$$ [LINE AMOUNT],
   APAMT [INVOICE AMOUNT],
   appym [PAID AMOUNT],
   APCHK [CHECK #],                          
   APITEM [BARCODE #],
   APSEQ [Line item]
 FROM  [AccountingDM].[dbo].[tblPpAPInv]               
   WHERE APVID in ('DWI006', 'CV2829', 'dw 007', 'dwi001')
      and apcdte between 20170101 and 20170331
 OFFSET 0 ROWS
 FETCH FIRST 1 ROW ONLY;