将2个表组合成一个查询

时间:2017-07-06 06:22:20

标签: postgresql

我在postgresql中每个附加了2个表Sales和Employees。 我需要计算: 查询返回2015年销售额最高的前4名员工。此外,已经离开公司的员工销售额应在员工编号999以下 提前谢谢你的帮助

Sales Employess

1 个答案:

答案 0 :(得分:0)

推荐的SQL已经过测试:

SELECT  
s.employee_id, emp.first_name,  
emp.last_name, s.department,  
sum(s.num_of_products) as total_product,  
sum(s.total_price) as total_price,  
s.branch_id, s.branch_city,  
s.date  
FROM sales s  
JOIN employees emp  
ON s.employee_id = emp.employee_id  
WHERE date_part('year',s.date) = '2014'  
-- '2014' is year depend on the input ex. '2015'  
GROUP BY s.employee_id, emp.first_name,emp.last_name,  
s.department, s.branch_id, s.branch_city, s.date  
-- add non aggregate function (sum,count,max,etc) field to group by if you want to show the field.  
-- not add in group by cause error 'field must appear in group by'
ORDER BY total_product  
-- order by total_product based on total_product  
-- order by for choose order by product or price using alias  
-- order by without alias ORDER BY sum(s.num_of_products)  
-- order by will be error caused error if use num_of_products  
-- order by total_price if the TOP 4 based on total_price  
LIMIT 4;   
-- top 4  
-- top n => LIMIT n