Sql-Server

SQL Server 2012 查詢:每個供應商狀態中最早日期的發票

  • August 18, 2016

我有桌子:

  1. 發票(VendorID、InvoiceDate、InvoiceNumber、InvoiceTotal、…)、
  2. 供應商(供應商名稱、供應商 ID、….)

我正在嘗試獲取每個供應商的最早發票列表,以及VendorName, InvoiceNumber, InvoiceDate, InvoiceTotal(對於該最早日期)。

這是我所擁有的:

SELECT VendorName, InvoiceNumber, InvoiceDate, InvoiceTotal 
FROM Vendors V JOIN Invoices I ON V.VendorID=I.VendorID
WHERE  InvoiceDate   <= ( SELECT  Min(InvoiceDate) 
                         FROM Invoices 
                         JOIN Vendors ON V.VendorID=Vendors.VendorID  )
GROUP BY VendorName, InvoiceNumber, InvoiceDate, InvoiceTotal

問題是我只收到一張發票,這是所有發票中最早的,而不是州最早的。到底是怎麼回事?

看起來您在查詢中的任何地方都沒有 InvoiceState。

這裡有更好的格式(PRE-COLUMN COMMA MASTERRACE!!

SELECT VendorName
, InvoiceNumber
, InvoiceDate
, InvoiceTotal 
FROM Vendors V 
JOIN Invoices I 
   ON V.VendorID=I.VendorID 
WHERE InvoiceDate <= ( SELECT Min(InvoiceDate) 
                      FROM Invoices 
                      JOIN Vendors 
                      ON V.VendorID=Vendors.VendorID ) 
GROUP BY VendorName
, InvoiceNumber
, InvoiceDate
, InvoiceTotal

將它 (InvoiceState) 添加到您的 SELECT 和 GROUP BY 將添加該級別的詳細資訊。我假設您需要將其添加為您的第一列(在 VendorName 之前)。

編輯:進一步看,似乎您的子查詢中也需要它。

引用自:https://dba.stackexchange.com/questions/147117