【发布时间】:2009-05-12 21:37:34
【问题描述】:
我有三个类似以下的表:
Customer (CustomerID, AddressState)
Account (AccountID, CustomerID, OpenedDate)
Payment (AccountID, Amount)
付款表可以包含一个帐户的多个付款,一个客户可以有多个帐户。
我想做的是按州逐月检索所有付款的总金额。例如
Opened Date| State | Total
--------------------------
2009-01-01 | CA | 2,500
2009-01-01 | GA | 1,000
2009-01-01 | NY | 500
2009-02-01 | CA | 1,500
2009-02-01 | NY | 2,000
换句话说,我试图找出各州每月支付的费用最多。我只对 OpenedDate 的月份感兴趣,但我将其作为之后处理的日期。我试图在一个查询中检索我需要的所有数据。
我一直在尝试以下方式:
select
dateadd (month, datediff(month, 0, a.OpenedDate), 0) as 'Date',
c.AddressState as 'State',
(
select sum(x.Amount)
from (
select p.Amount
from Payment p
where p.AccountID = a.AccountID
) as x
)
from Account a
inner join Customer c on c.CustomerID = a.CustomerID
where ***
group by
dateadd(month, datediff(month, 0, a.OpenedDate), 0),
c.AddressState
where 子句包括 Account 表中的一些常规内容。该查询将不起作用,因为 a.AccountID 未包含在聚合函数中。
我是否以正确的方式处理这个问题?如何检索我需要的数据以计算哪些州的客户支付最多?
【问题讨论】:
标签: sql sql-server