Sql 单独表上的聚合函数
我正在尝试从一张表中选择最近日期,并将其发送给另一张表中的客户。我找的不是一个客户,而是几个。我想做的事情如下所示:Sql 单独表上的聚合函数,sql,sql-server,join,aggregate-functions,max,Sql,Sql Server,Join,Aggregate Functions,Max,我正在尝试从一张表中选择最近日期,并将其发送给另一张表中的客户。我找的不是一个客户,而是几个。我想做的事情如下所示: select C.[Last Name], C.[First Name], C.[State], I.[Date] From myDb.dbo.Customer C left join myDb.dbo.Invoice I on I.CustomerID = C.CustomerID where c.state=@State and i.date = max(i.da
select C.[Last Name], C.[First Name], C.[State], I.[Date]
From myDb.dbo.Customer C
left join myDb.dbo.Invoice I on I.CustomerID = C.CustomerID
where c.state=@State and i.date = max(i.date)
我知道我不能在where中使用Max,我试着使用have。我无法为customerID分配本地变量并执行where I.date=select。。。。我试图将所有这些都作为一条语句来保存,因为这是在单个数据库的多个数据库上执行的
更新:
我决定更改我的设计要求,因为这不是最理想的解决方案。您可能希望分组:
select C.[Last Name], C.[First Name], C.[State], max(I.[Date]) as [Date]
from myDb.dbo.Customer C
left join myDb.dbo.Invoice I on I.CustomerID = C.CustomerID
where C.state = @State
group by C.[Last Name], C.[First Name], C.[State]
更新:
select A.[Last Name], A.[First Name], A.[State], B.[Date]
from myDb.dbo.Customer A
join (
-- Get Customers by State with their most recent Invoice Date
select C.[CustomerID], max(I.[Date]) as [Date]
from myDb.dbo.Customer C
left join myDb.dbo.Invoice I on I.[CustomerID] = C.[CustomerID]
where C.[State] = @State
group by C.[CustomerID]
) B on A.[CustomerID] = B.[CustomerID]
派生表返回每个客户的最后发票日期。然后将其与customer连接起来
select C.[Last Name], C.[First Name], C.[State], LastInvoice.LastInvoiceDate
from myDb.dbo.Customer C
inner join
(
select I.CustomerID, max (I.Date) LastInvoiceDate
from myDb.dbo.Invoice I
group by I.CustomerID
) LastInvoice
on C.CustomerID = LastInvoice.CustomerID
如果客户在同一天有更多发票,则可能会出现重复,假定日期不包含时间成分。您可以用distinct进行分类。不确定我是否理解这个问题。您希望获得特定州的所有客户及其各自上次发票日期的列表?为什么一张发票上会有多个客户?这将是所有客户以及哪个州的列表,以及每个客户的最新发票日期。遗憾的是,如果客户已移到不同的州,我得到了一个重复的结果,我不确定我是否理解where子句,但是我提出了另一种可能性。你证明是最有帮助的,因此,我将此标记为答案,以结束问题。谢谢你的帮助。决定改变一下设计。
select C.[Last Name], C.[First Name], C.[State], I.[Date] ,
(select top 1 date from invoice I where I.CustomerID = C.CustomerID order by date desc)
From myDb.dbo.Customer C
select C.[Last Name], C.[First Name], C.[State], LastInvoice.LastInvoiceDate
from myDb.dbo.Customer C
inner join
(
select I.CustomerID, max (I.Date) LastInvoiceDate
from myDb.dbo.Invoice I
group by I.CustomerID
) LastInvoice
on C.CustomerID = LastInvoice.CustomerID