gpt4 book ai didi

MySQL - 如何限制每个 ID 的结果?

转载 作者:行者123 更新时间:2023-11-29 05:58:03 25 4
gpt4 key购买 nike

我有以下查询,它创建了一个 View 表,显示商店中最高级别的销售人员以及其他一些详细信息:

CREATE OR REPLACE VIEW sales_data AS 
SELECT s.storename AS "Store",
e.employee_name AS "Employee",
e1.employee_name AS "Manager",
SUM(p.total_sale_value) AS "Sales Value"
FROM fss_Shop s
JOIN Employee e ON e.storeid = s.storeid
JOIN Payment p ON p.employee_number = e.employee_number
JOIN Employee e1 ON e1.employee_number = e.manager_number
WHERE s.storeid=1
GROUP BY e.employee_name
ORDER BY SUM(p.total_sale_value) DESC LIMIT 1;

上面的查询将只显示单个商店的销售数据,原因如我所述WHERE s.storeid=1。我的 table 上有 20 家商店。我怎样才能更改上述查询,以便它为我提供 20 家商店的销售数据(即 20 行)。

最佳答案

CREATE OR REPLACE VIEW employee_sales_totals AS
SELECT
e.*,
SUM(p.total_sale_value) AS total_sale_value
FROM
Employee e
INNER JOIN
Payment p
ON p.employee_number = e.employee_number
GROUP BY
e.id -- This should be the Primary Key / Surrogate Key of the employee table
;

CREATE OR REPLACE VIEW shop_top_employee_by_sales_value AS
SELECT
s.storename AS "Store",
e.employee_name AS "Employee",
m.employee_name AS "Manager",
p.total_sale_value AS "Sales Value"
FROM
(
SELECT storeid, MAX(total_sale_value) AS total_sale_value
FROM employee_sales_totals
GROUP BY storeid
)
p
INNER JOIN
employee_sales_totals e
ON e.storeid = p.storeid
AND e.total_sale_value = p.total_sale_value
INNER JOIN
fss_Shop s
ON s.storeid = e.storeid
INNER JOIN
Employee m
ON m.employee_number = e.manager_number
;

根据您对上一个问题的回答,如果多个员工在同一家商店中获得相同的总销售额,则所有这些员工都将被退回。

关于MySQL - 如何限制每个 ID 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47533531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com