我正在尝试查找每个销售人员的每个销售商品的总销售数量
销售人员可以从一个商店转移到另一个商店(因为所有商店都由一个人拥有)。
销售人员可以映射到n个商店,但是目前他应该被分配到一个商店
以例如'John'与sale_person_id = 1在shop_id = 1中工作,期间为“2015-06-01 08:00:00”至“2015-06-01 13:00:00”但现在他正在shop_id = 2工作,他仍然在那里工作,因为他的end_working_date是NULL
输出应为:
sale_person_login_id shop_name count(*)
John Shop1 2
John Shop2 3
David Shop2 1
Jenna Shop3 1
这是sqlfiddle http://sqlfiddle.com/#!9/a8d2e/3
因为期间'2015-06-01 08:00'和'2015-06-01 18:00' 约翰在2家商店工作,分别是shop1和shop2,他在shop1工作时卖了2件商品,当他在shop2时卖了3件商品
但问题是我的输出是
sale_person_login_id shop_name count(*)
John Shop1 5
John Shop2 5
David Shop2 1
Jenna Shop3 1
这是我正在使用的查询
select sale_person.sale_person_login_id, shop.shop_name ,count(*) from sale
join sale_person on
sale.sale_person_id = sale_person.sale_person_id
join sale_person_shop
on sale_person_shop.sale_person_id = sale.sale_person_id
join shop on shop.shop_id = sale_person_shop.shop_id
WHERE sale.sale_date BETWEEN '2015-06-01 08:00' AND '2015-06-01 18:00'
GROUP BY sale_person.sale_person_login_id, shop.shop_name ;
答案 0 :(得分:1)
您的查询未将sale
与shop
相关联。也就是说,您的查询不知道哪个shop
创建了sale
,因此它将sale
与user_shop
中的每一行匹配。
此外,2015年已经......时间放弃了连接操作的旧式逗号语法(使用JOIN
关键字),并将连接谓词移到{{1}条款。
ON
实际上,我不认为 SELECT u.login_id
, shop.shop_name
, COUNT(*)
FROM sale s
JOIN user u
ON u.user_id = s.user_id
JOIN shop
ON shop.shop_id = s.shop_id -- this condition is missing from your query
JOIN user_shop us
ON us.shop_id = shop.shop_id
AND us.user_id = u.user_id
WHERE s.sale_date BETWEEN '2015-06-01 08:00' AND '2015-06-01 18:00'
GROUP BY s.user_id, shop.shop_name
表需要参与查询,假设user_shop
是唯一的,并且目的不是限制某些行来自(user_id,shop_id)
被退回。可以从查询中省略sale
表:
user_shop
SELECT u.login_id
, shop.shop_name
, COUNT(*)
FROM sale s
JOIN user u
ON u.user_id = s.user_id
JOIN shop
ON shop.shop_id = s.shop_id -- this condition is missing from your query
WHERE s.sale_date BETWEEN '2015-06-01 08:00' AND '2015-06-01 18:00'
GROUP BY s.user_id, shop.shop_name
是sale
的{{1}},user
的{{1}}是sale
。
但是shop
{(1}}可以{(1)}多个user
。这就是原始查询返回膨胀计数的原因。
答案 1 :(得分:1)
我认为你正在寻找类似的东西 - 尽管我并不十分清楚“销售”与“销售”之间的关系。和'项目' ...
SELECT u.login_id
, s.shop_name
, COUNT(l.sale_id) total_sales
FROM user u
JOIN user_shop us
ON us.user_id = u.user_id
JOIN shop s
ON s.shop_id= us.shop_id
JOIN sale l
ON l.user_id = us.user_id
AND l.sale_date BETWEEN us.start_working_date AND COALESCE(us.end_working_date,CURDATE())
WHERE l.sale_date BETWEEN '2015-06-01 08:00:00' AND '2015-06-01 18:00:00'
GROUP
BY u.login_id
, s.shop_name;