我正在处理一个SQL查询,在该查询中我想根据一个字段的最频繁出现将两个表联接在一起。
有一个我想从中获得最频繁订单的特定餐厅的餐厅表。 这些食物可由同一家餐厅的多个不同的人订购。我想获得每个餐厅中最常出现的商品的结果,并且想要该商品中最常请求的人。
appveyor
我想要的,
||
我目前有以下脚本:
Table Restaurants
Restaurant
=======
R1
R2
Table Orders
Item RequestedBy Restaurant Date
==========================================
B1 A R1 123
B1 B R1 234
B2 C R2 456
B1 A R1 567
当前返回的数据如下:
Restaurant Item RequestedBy
============================
R1 B1 A
R2 B2 C
任何帮助将不胜感激!谢谢
答案 0 :(得分:0)
假设给定的Orders表包含一些不合适的数据,并且请求将按照描述进行查找
“以获取每个餐厅中最常出现的商品的结果” 然后进入
“我想要最常提出要求的人”
我建议保持其简单性,并在视图中拆分任务,例如
Create View V_OrdersPerRestaurant_Item as
Select Restaurant,Item, COUNT(*) as Orders
from [dbo].[orders]
group by Restaurant,Item
Create View V_MaxSelectItemPerRestaurant as
Select * from V_OrdersPerRestaurant_Item ov
where Orders = (Select Max(Orders) from V_OrdersPerRestaurant_Item where ov.Restaurant=Restaurant)
Create View V_MaxSelectItemPerRestaurantAndRequestedBy as
Select ms.Item,ms.Restaurant,o.RequestedBy,Count(*) as Requests from V_MaxSelectItemPerRestaurant ms
join [dbo].[orders] o on ms.Item=o.Item and ms.Restaurant=o.Restaurant
group by ms.Item,ms.Restaurant,o.RequestedBy
应允许通过以下方式获得预期结果:
Select * from V_MaxSelectItemPerRestaurantAndRequestedBy ov
where Requests=(Select max(Requests) from V_MaxSelectItemPerRestaurantAndRequestedBy iv where iv.Item=ov.Item and ov.Restaurant=iv.Restaurant)
答案 1 :(得分:0)
我认为最简单的方法是使用apply
:
select r.restaurant, ri.item, rir.requestedby
from restaurant r cross apply
(select top (1) o.item, count(*) as cnt
from orders o
where o.restaurant = r.restaurant
order by count(*) desc
) ri cross apply
(select top (1) o2.requrestedby, count(*) as cnt
from orders o2
where o2.restaurant = r.restaurant and
o2.item = r.item
order by count(*) desc
) rir;
另一种可行的方法是使用窗口功能的order by
:
select top (1) with ties restaurant, item, requestedby
from (select o.restaurant, o.item, o.requestedby,
count(*) as rir_cnt,
sum(count(*)) over (partition by o.restaurant, o.item) as ri_cnt
from orders o
group by o.restaurant, o.item, o.requestedby
) rir
order by row_number() over (partition by restaurant order by ri_cnt desc),
row_number() over (partition by restaurant, item order by rir_cnt desc);