我必须每周从Customer
(客户名称,ID)和order
(订单ID,订单日期,订单日期)中找到3个最高消费客户。如果我今天运行查询,它应显示订单日期存在的所有周的前3位。
我正在考虑在约会(每周)上做Partition by
,但我找不到任何方法来做到这一点?有人做过每周一次的结果分区吗?
我知道这不对,但这就是我所拥有的:
Select Top 3 customer_name, id OVER (partition by [week])
(
Select c.customer_name, c.id, o.order_amt,
from customer c
Join Order o
on c.id=o.id
group by c.id
)
答案 0 :(得分:0)
查询应该是这样的
O(n)
答案 1 :(得分:0)
根据您的表格结构,orders.order_id
为customer.id
使用此声明
select
*
from
(
select
details.*
,dense_rank() over (partition by week_num order by order_amt desc) as rank_num
from
(
select
c.id as customer_id
,c.name
,sum(o.order_amt) as order_amt
,datepart(WEEK,o.order_date) as week_num
from customer c
join orders o on c.id=o.order_id
group by c.id,c.name,datepart(WEEK,o.order_date)
)details
)dets
where dets.rank_num<=3
更新:已更改语句仅使用2个表
答案 2 :(得分:0)
这是一个想法,
;WITH CTE
AS (
SELECT c.customer_name
,c.id
,o.order_amt
,datepart(wk, datecol) AS Weekcol
)
,CTE1
AS (
SELECT c.customer_name
,c.id
,o.order_amt
,ROW_NUMBER() OVER (
PARTITION BY Weekcol ORDER BY order_amt DESC
) AS rowNUm
FROM CTE
)
SELECT *
FROM CTE1
WHERE rowNUm <= 3