SQL查询,用于计算特定年份中超过2个订单
我有两张桌子。带列的销售代表:SRepID、SRepName、SRepPhone 具有以下列的订单:OrderID、CustomerID、SRepID、OrderDate 我需要退回2019年至少处理过两份订单的所有SRepName 我完全迷失在这一点上,希望能朝着正确的方向努力SQL查询,用于计算特定年份中超过2个订单,sql,mysql-workbench,Sql,Mysql Workbench,我有两张桌子。带列的销售代表:SRepID、SRepName、SRepPhone 具有以下列的订单:OrderID、CustomerID、SRepID、OrderDate 我需要退回2019年至少处理过两份订单的所有SRepName 我完全迷失在这一点上,希望能朝着正确的方向努力 我正在SQL Workbench中执行此操作。您可以使用相关子查询来计算每个销售代表的订单数: select s.* from salesrep s where ( select count(*) f
我正在SQL Workbench中执行此操作。您可以使用相关子查询来计算每个销售代表的订单数:
select s.*
from salesrep s
where (
select count(*)
from orders o
where
o.repId = s.sRepId
and o.orderDate >= '2019-01-01'
and o.orderDate < '2020-01-01'
) >= 2
也可以使用聚合。这要求您枚举要返回的列,但也允许您对订单使用聚合函数:
select
s.sRepId,
s.sRepName,
count(*) no_orders,
max(o.OrderDate) last_order_date
from salesrep s
inner join orders o on o.repId = s.sRepId
where o.orderDate >= '2019-01-01' and o.orderDate < '2020-01-01'
group by s.sRepId, s.sRepName
having count(*) > 1
哇,看起来真的很先进!有没有更基本的方法来实现这一点?我在我的原始帖子中输入了一个错误,RepID应该被重新排序。谢谢你的快速回复!伟大的我刚刚从GMB的回复中添加了日期部分,它起作用了!谢谢大家!@莫妮卡哈哈,我只是注意到我错过了。添加它以使答案100%正确
select SRepName from salesReps
inner join Orders on salesReps.SRepID = orders.SRepID
where orderDate >= '2019-01-01' and orderDate < '2020-01-01'
group by sRepName
having count(OrderId) >1
select SRepName
,count(OrderID)
from salesreps s
inner join orders o
on s.SRepID = o.SRepID
where year(OrderDate) = '2019'
group by SRepName
having count(OrderID) >= 2