2010-06-14 46 views
4

我有一個公司的表是dbo.companiescompanyId作爲列。我還有一張發票表,其中dbo.invoicesinvoicecompanyId列(與另一張表上的companyId相同),它也有一個名爲invoicedate的列。 我試圖實現的是每個companyid的視圖以及我所有公司對應的最新發票日期。我需要做一個SQL查看返回每個公司的最新發票日期

我也做了以下的,但我不知道如何爲最新的發票進行過濾,將返回所有公司的所有發票,我需要你能幫請所有公司

SELECT  TOP (100) PERCENT 
    'A' + 
    SUBSTRING('000000', 1, 6 - LEN(CAST(dbo.companies.companyId AS varchar(10)))) + 
    CAST(dbo.companies.companyId AS varchar(10)) AS Client_ID, 
    dbo.invoices.invoiceDate AS S_Inv_Date 
FROM dbo.invoices 
INNER JOIN dbo.companies 
ON dbo.invoices.invoiceCompanyId = dbo.companies.companyId 
ORDER BY Client_ID 

最新發票嗎?

TA

回答

1
SELECT 
     SUBSTRING('000000', 1, 6 - LEN(CAST(dbo.companies.companyId AS varchar(10)))) + 
      CAST(dbo.companies.companyId AS varchar(10)) AS Client_ID 
    , b.mxDate maxInvoiceDate 
    FROM dbo.companies c 
    , (SELECT dbo.invoices.invoiceCompanyId companyId 
      , MAX(dbo.invoices.invoiceDate) mxDate 
      FROM dbo.invoices 
     GROUP BY dbo.invoices.invoiceCompanyId) b 
WHERE c.companyId = b.companyId 
ORDER BY 1 
+0

喜,即工作一種享受,謝謝 – 2010-06-14 16:01:53

+3

惡,在轉換ANSI-92 ANSI-89連接語法?並在順序中使用了... – 2010-06-14 16:13:28

+0

嘿,它的工作沒有它:)。我更喜歡上面使用的連接語法,它不那麼羅嗦,它使得WHERE子句看起來更好看,如果你加入許多表恕我直言。老派沒有錯,對吧? :)。 – dcp 2010-06-14 16:22:11

0

你能order by S_Inv_Date descending獲得所需要的結果嗎?

+0

喜,它沒有​​爲我工作,但由於 – 2010-06-18 10:09:23

0

我會使用GROUP BY和MAX。快速&髒樣品:

SELECT cy.companyId, cy.CompanyName, max(inv.invoiceDate) as LastInv 
FROM companies as cy, invoices as inv 
GROUP BY cy.companyId, cy.CompanyName 
WHERE cy.companyId = inv.companyId 
相關問題