查询以列出具有多个客户的所有发票

时间:2013-11-22 18:20:36

标签: sql sql-server

这是两个表的简化版本:

Invoice
========
InvoiceID
CustomerID
InvoiceDate
TransactionDate
InvoiceTotal

Customer
=========
CustomerID
CustomerName

我想要的是所有发票的清单,其中每个客户有多个发票。我不想对发票进行分组或计数,实际上我需要查看所有发票。输出看起来像这样:

CustomerName    TransactionDate    InvoiceTotal
-------------------------------------------------
Ted Tester      2012-12-14         335.49
Ted Tester      2013-02-02         602.00
Bob Beta        2013-05-04         779.50
Bob Beta        2013-07-07          69.00
Bob Beta        2013-09-10         849.79

为SQL Server编写查询以实现此目的的最佳方法是什么?

3 个答案:

答案 0 :(得分:2)

使用窗口函数可以做到这一点 - SQL Server 2005及更高版本将支持这一功能:

SELECT CustomerName, TransactionDate, InvoiceTotal
FROM (
  SELECT c.CustomerName, i.TransactionDate, i.InvoiceTotal, 
         COUNT(*) OVER (PARTITION BY i.CustomerId) as InvoiceCount
  FROM Invoice i
  JOIN Customer c ON i.CustomerId = c.CustomerId
) t
WHERE InvoiceCount > 1

答案 1 :(得分:1)

这应该做:

SELECT  C.CustomerName,
        I.TransactionDate,
        I.InvoiceTotal
FROM dbo.Invoice I
INNER JOIN dbo.Customer C
    ON I.CustomerID = C.CustomerID
WHERE EXISTS(SELECT 1 FROM Invoice
             WHERE CustomerID = I.CustomerID
             GROUP BY CustomerID
             HAVING COUNT(*) > 1)

SQL Server 2005 +的另一种方式:

;WITH CTE AS
(
    SELECT  C.CustomerName,
            I.TransactionDate,
            I.InvoiceTotal,
            N = COUNT(*) OVER(PARTITION BY I.CustomerID)
    FROM dbo.Invoice I
    INNER JOIN dbo.Customer C
        ON I.CustomerID = C.CustomerID
)
SELECT *
FROM CTE
WHERE N > 1

答案 2 :(得分:0)

旧的GROUP BY使用IN子句进行子选择:

SELECT c2.CustomerName, i2.TransactionDate, i2.InvoiceTotal
FROM Invoice i2
    INNER JOIN Customer c2 ON i2.CustomerID = c2.CustomerID
WHERE i2.CustomerID IN (
    SELECT c.CustomerID
    FROM Customer c
        INNER JOIN Invoice i on i.CustomerID = c.CustomerID
    GROUP BY c.CustomerID
    HAVING COUNT(i.InvoiceID) > 1
)