我的公司表格为dbo.companies
,并且companyId
为列。我还有一个dbo.invoices
的发票表,其中invoicecompanyId
列(与另一个表中的companyId
相同),并且还有一个名为invoicedate
的列。
我想要实现的是每个companyid
的视图,以及我所有公司的相应最新发票日期。
我已完成以下操作,但我不知道如何过滤最新发票,它会返回所有公司的所有发票,我需要所有公司的最新发票
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
答案 0 :(得分: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
答案 1 :(得分:0)
您可以order by S_Inv_Date descending
获得所需的结果吗?
答案 2 :(得分: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