我有三个表,即a_sws,b_sws,c_sws。 它们都具有如下所示的相同列。
salesman_id salesman_name product_price product_quantity
通过使用此查询,我可以在单个表格中获得前5名最高销售额:
SELECT salesman_id, salesman_name ,
SUM(product_price * product_quantity) AS TotalSales
FROM a_sws
GROUP BY salesman_id
ORDER BY SUM(product_price * product_quantity) DESC
LIMIT 5;
如何从三张表中获得前五名的销量?
答案 0 :(得分:2)
如果我假设您要在三个表中汇总销售人员的记录,那么我会想到union all
:
SELECT salesman_id, salesman_name,
SUM(product_price * product_quantity) AS TotalSales
FROM ((SELECT salesman_id, salesman_name, product_price, product_quantity
FROM a_sws
) UNION ALL
(SELECT salesman_id, salesman_name, product_price, product_quantity
FROM b_sws
) UNION ALL
(SELECT salesman_id, salesman_name, product_price, product_quantity
FROM c_sws
)
) abc
GROUP BY salesman_id
ORDER BY TotalSales DESC
LIMIT 5;
现在进行一些评论。您不应将销售员ID和名称与实际销售额存储在同一个表中。身份是足够的;你应该在SalesPerson
表中查找名称。
此外,您不应该有三个具有相同信息的表。这些数据应该放在一个表中,可能有一个列来标识"类型"或用于拆分原始数据的时间范围。