MySQL - How to limit one result per ID?

前端 未结 2 471
悲哀的现实
悲哀的现实 2021-01-23 01:40

I have the following query which creates a view table showing the highest salesperson in a store with few other details:

CREATE OR REPLACE VIEW sales_data AS 
SE         


        
2条回答
  •  爱一瞬间的悲伤
    2021-01-23 02:19

    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 
    ;
    

    As per the answer to your previous question, if multiple employees are tied for the same total sales amount in the same store, all such employees would be returned.

提交回复
热议问题