单独表上的聚合函数

时间:2012-03-27 21:14:37

标签: 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.date)

我知道我不能在Max()位置,我尝试使用HAVING。我无法为customerID分配本地变量并执行where i.date = (select...)。我试图将这一切保持为一个声明,因为这是从一个数据库中的几个DB上执行的。

更新:
我决定改变我的设计要求,因为这不是最理想的解决方案。

4 个答案:

答案 0 :(得分:1)

您可能想要分组:

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]

答案 1 :(得分:1)

;with cte as
(
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 
) select * from cte where cte.Date = (select max (cte.Date) from cte)

答案 2 :(得分:1)

派生表返回每个客户的最后发票日期。然后与客户联系。

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进行排序。

答案 3 :(得分:0)

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