帮助输出中的重复项

时间:2010-10-15 13:32:10

标签: sql sql-server tsql sql-server-2008

我需要一些帮助,让我的副本在我的输出中不止一次显示。

SELECT 
  accountNumber AS 'Member Number',  
  OD.orderdetails AS 'iNum', 
  FirstName AS 'First Name', 
  LastName AS 'Last Name', 
  HGP.email AS 'Email', 
  points AS 'Points -->', 
  '$' + CONVERT(varchar(50),(CONVERT(int,Points) * .1)) AS '<-- Amount', 
  CountryCode AS 'Country', 
  CONVERT(VARCHAR(10), issued, 101) AS 'Order Date', 
  CONVERT(VARCHAR(10), cs.RedeemedDate, 101) AS 'R Date' 
FROM tblHGP HGP, OrderDetails OD, tblInvoices i
JOIN tblCS cs ON i.InvoiceNumber = cs.InvoiceNumber
JOIN tblECI ac ON i.InvoiceNumber = ac.InvoiceNumber 
  AND cs.Sold = ac.ECIID
WHERE 
  i.InvoiceNumber = HGP.invoiceNumber 
  AND HGP.issued BETWEEN '2010-01-01' AND '2010-09-01' 
  AND HGP.invoiceNumber = OD.orderdetails
ORDER BY 
  HGP.issued

就像我上面说的那样,我在一些用户身上得到了重复。我尝试过 distinct ,但似乎无法正常工作。

任何帮助都会很棒! :O)

大卫

2 个答案:

答案 0 :(得分:2)

更多细节。从查询看,只要发票有多个订单明细(订购了多个商品),您就会得到一个双倍。这看起来像是设计。当然,dsictinct不起作用,因为并非所有字段都是相同的。

基本上,如果用户在一张发票中为2件物品开具发票,他将会出现(和发票一样)两次。

答案 1 :(得分:1)

在我看来,您只使用了对OrderDetails的连接:

OD.orderdetails AS 'iNum',

如您的where子句所示,您可以从HGP获得相同的值:

AND HGP.invoiceNumber = OD.orderdetails

因此,您可以消除整个OD的连接,并消除由于发票的详细信息表中的多行而导致的重复。所以,重写它应该是这样的:

  SELECT 
  accountNumber AS 'Member Number',  
  HGP.invoiceNumber AS 'iNum', 
  FirstName AS 'First Name', 
  LastName AS 'Last Name', 
  HGP.email AS 'Email', 
  points AS 'Points -->', 
  '$' + CONVERT(varchar(50),(CONVERT(int,Points) * .1)) AS '<-- Amount', 
  CountryCode AS 'Country', 
  CONVERT(VARCHAR(10), issued, 101) AS 'Order Date', 
  CONVERT(VARCHAR(10), cs.RedeemedDate, 101) AS 'R Date' 
FROM tblHGP HGP, tblInvoices i
JOIN tblCS cs ON i.InvoiceNumber = cs.InvoiceNumber
JOIN tblECI ac ON i.InvoiceNumber = ac.InvoiceNumber 
  AND cs.Sold = ac.ECIID
WHERE 
  i.InvoiceNumber = HGP.invoiceNumber 
  AND HGP.issued BETWEEN '2010-01-01' AND '2010-09-01' 
ORDER BY 
  HGP.issued

我无法确定非表限定列名称(即已发布,Points,CountryCode,FirstName,LastName)是否来自OrderDetails,尽管它们看起来不像。