我在组合两个MySQL查询并获取正确的数据时遇到了很多麻烦。
我的第一个查询如下:
SELECT e.employee_id,
e.employee_name,
COUNT(s.sale_id) AS employee_sales
FROM employees e,
sales s,
days d
WHERE s.sale_id = '$sale_type'
AND d.day_year_id = '$year'
AND s.sale_day_id = d.day_id
AND e.employee_id = s.sale_employee_id
GROUP BY e.employee_id
然后,在每个员工结果上,我执行三个查询以获取有关每个员工的具体信息:
首先,为了获得他们工作的总分钟数,我执行以下查询。当我尝试将第一个与第一个一起加入时,无论他们是否在特定日期进行了销售,我都无法返回他们工作的所有会议记录:
SELECT SUM(employee_day_end_minute-employee_day_start_minute) AS employee_minutes
FROM employee_days ed,
days d
WHERE ed.employee_days_employee_id = '$employee_id'
AND ed.employee_days_day_id = d.day_id
AND d.day_year_id = '$year'
其次,要获得他们最有效的工作类型:
SELECT ed.employee_day_position,
COUNT(ed.employee_day_position) AS count
FROM employee_days ed,
days d
WHERE ed.employee_days_employee_id = '$employee_id'
AND ed.employee_days_day_id = d.day_id
AND d.day_year_id = '$year'
GROUP BY match_player_position
ORDER BY count DESC LIMIT 1
最后,我获得了一个平均权重,可以根据他们工作的日期和时间乘以销售额:
SELECT (SUM(dw.day_weighting_value)/COUNT(s.day_weighting_value)) AS employee_weigting
FROM employee_days ed,
day_weightings dw,
days d
WHERE ed.employee_day_employee_id = '$employee_id'
AND ed.employee_day_day_id = d.day_id
AND d.day_year_id = '$year'
AND dw.day_weighting_day_id = d.day_id
AND dw.day_weighting_minute >= ed.employee_day_start_minute
AND dw.day_weighting_minute <= ed.employee_day_end_minute`
任何人都可以向我提供有关这是否可行的指导,如果有的话,从哪里开始呢?
提前致谢!
答案 0 :(得分:1)
第一个和第三个查询很容易加入。您只需编写一个子查询,该子查询返回为每个员工ID分组的结果,并将这些子查询连接到原始查询。
SELECT p.employee_id,
e.employee_name,
COUNT(s.sale_id) AS employee_sales,
ed.employee_minutes,
edw.employee_weighting
FROM employees e
JOIN sales s ON e.employee_id = s.sale_employee_id
JOIN days d ON s.sale_day_id = d.day_id
JOIN (SELECT ed.employee_days_employee_id, SUM(employee_day_end_minute-employee_day_start_minute) AS employee_minutes
FROM employee_days ed
JOIN days d ON ed.employee_days_day_id = d.day_id
WHERE d.day_year_id = '$year'
GROUP BY ed.employee_days_employee_id) AS ed ON ed.employee_days_employee_id = e.employee_id
JOIN (SELECT ed.employee_days_employee_id, (SUM(dw.day_weighting_value)/COUNT(s.day_weighting_value)) AS employee_weigting
FROM employee_days ed
JOIN day_weightings dw ON dw.day_weighting_minute >= ed.employee_day_start_minute
AND dw.day_weighting_minute <= ed.employee_day_end_minute
days d ON dw.day_weighting_day_id = d.day_id
AND ed.employee_day_day_id = d.day_id
WHERE d.day_year_id = '$year'
GROUP BY ed.employee_days_employee_id) AS edw ON edw.employee_days_employee_id = e.employee_id
WHERE s.sale_id = '$sale_type'
AND d.day_year_id = '$year'
GROUP BY e.employee_id
中间查询更难。可能有一种方法可以将其写为单个查询,返回按员工分组的最高职位,但我现在无法想到它。