SQL之间的date子句引用多个日期范围

时间:2019-01-08 21:22:03

标签: sql-server tsql

我有两个要合并的SQL客户表。

CustomerDate:
Column 1: customerkey int
Column 2: RecentPurchase smalldatetime- the date of their most recent purchase
Column 3: PriorYear smalldatetime - the RecentPurchase date minus a year

CustomerTrans:
Column 1: Transactionkey int
Column 2: customerkey int
Column 3: TransactionDate smalldatetime- Date of Transaction
Column 4: Amount - Total Amount Spent

我想获得一个客户在他们最近的购买到上一个购买日期之间花费的总金额。我已经尝试了以下查询,但未返回任何结果。

select t.customerkey, 
       sum(t.amount)
from customertrans t
inner join customerdate d on t.customerkey = d.customerkey
where  TransactionDate between RecentPurchase and PriorYear
group by t.customerkey

如何运行查询,以便每个客户的TransactionDate由CustomerDate表中的日期确定?

1 个答案:

答案 0 :(得分:0)

也许你只是想要:

where TransactionDate between PriorYear and RecentPurchase

代替:

where TransactionDate between RecentPurchase and PriorYear