Mysql
 sql >> база данни >  >> RDS >> Mysql

MySQL - Как да филтрирам и показвам максимална стойност от група?

Едно възможно решение е да използвате HAVING и ALL

SELECT s.shopname AS "Store",
   e.empname AS "Employee",
   e1.empname AS "Manager",
   SUM(p.amount) AS "Total Sales"
FROM fss_Shop s
   JOIN fss_Employee e ON e.shopid = s.shopid
   JOIN fss_Payment p ON p.empnin = e.empnin
   JOIN fss_Employee e1 ON e1.empnin = e.mgrnin
GROUP BY e.empname, s.shopid
HAVING SUM(p.amount) >= ALL(
   SELECT SUM(p.amount)
   FROM fss_Employee e
   JOIN fss_Payment p ON p.empnin = e.empnin
   WHERE e.shopid = s.shopid
   GROUP BY e.empname
)

ако ALL не работи за вас. Можете да го промените по този начин

SELECT s.shopname AS "Store",
   e.empname AS "Employee",
   e1.empname AS "Manager",
   SUM(p.amount) AS "Total Sales"
FROM fss_Shop s
   JOIN fss_Employee e ON e.shopid = s.shopid
   JOIN fss_Payment p ON p.empnin = e.empnin
   JOIN fss_Employee e1 ON e1.empnin = e.mgrnin
GROUP BY e.empname, e.shopid
HAVING SUM(p.amount) = (
   SELECT MAX(t.samount)
   FROM
   (
     SELECT SUM(p.amount) samount
     FROM fss_Employee emp
     JOIN fss_Payment p ON p.empnin = emp.empnin
     WHERE emp.shopid = e.shopid
     GROUP BY emp.empname
   ) t
)

добре и следващата версия, която избягва корелирана подзаявка зад FROM

SELECT s.shopname AS "Store",
   e.empname AS "Employee",
   e1.empname AS "Manager",
   SUM(p.amount) AS "Total Sales"
FROM fss_Shop s
   JOIN fss_Employee e ON e.shopid = s.shopid
   JOIN fss_Payment p ON p.empnin = e.empnin
   JOIN fss_Employee e1 ON e1.empnin = e.mgrnin
GROUP BY e.empnin, e.shopid
HAVING (e.shopid, SUM(p.amount)) IN
(
  SELECT t.shopid, MAX(t.samount)
  FROM 
  (
     SELECT emp.shopid, SUM(p.amount) samount
     FROM fss_Employee emp
     JOIN fss_Payment p ON p.empnin = emp.empnin
     GROUP BY emp.empname, emp.shopid
  ) t
  GROUP BY t.shopid
) 



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. MySQL грешка № 121

  2. Конструкция на SQL заявка - разделяне на данни в колона в две колони

  3. Възможно ли е да се използват множество/вложени MySQLi изрази?

  4. Групиране по първа буква, по азбучен ред, най-добрият начин?

  5. Сигурно съхранявайте потребителите на Android Firebase Auth в база данни на MySQL