我正在尝试查找最大订单日期(表示最近的订单日期)和第二个最后订单日期(表示最后一次购买)
输出看起来像这样
datetime.strptime()
答案 0 :(得分:0)
嗯。怎么样?
select c.customerid, min(o.orderdate), max(o.orderdate), sum(o.paymentamount)
from customers c cross apply
(select top (2) o.*
from orders o
where o.customerid = c.customerid
order by o.orderdate desc
) o
group by c.customerid;
您也可以使用row_number()
执行此操作,但我今天正在练习横向连接。
注意:这省略了日期比较(因为文字说明没有提到它们)和金额的最终格式。
编辑:
使用row_number()
的等效查询效率可能稍低:
select c.customerid, min(o.orderdate), max(o.orderdate), sum(o.paymentamount)
from customers c join
(select o.*, row_number() over (partition by o.customerid order by o.oderdate desc) as seqnum
from orders o
) o
on o.customerid = c.customerid and o.seqnum <= 2
group by c.customerid;
ý