简体   繁体   中英

MySQL query with COUNT(*) and MAX() returning multiple columns

I am creating a small database to track appearances in Star Wars films. I am trying to write a query to return the actor with the most appearances. My subquery is working correctly.

SELECT 
    actor.ACT_FNAME AS 'First Name',
    actor.ACT_LNAME AS 'Last Name',
    COUNT(*) AS 'Total'
FROM
    appearance,
    actor
WHERE
    appearance.ACT_ID = actor.ACT_ID
GROUP BY appearance.ACT_ID
ORDER BY Total DESC;

This gives query gives back the actor first and last name as well as the total number of appearances (the results are a lot longer, cut for brevity): Image

Currently I am trying to use MAX() on the Total. This works correctly and returns the largest from the Total, but I am unsure how to attach the First and Last name fields along with this.

SELECT 
    MAX(Total) AS 'Total Appearances'
FROM
    (SELECT 
        actor.ACT_FNAME AS 'First Name',
            actor.ACT_LNAME AS 'Last Name',
            COUNT(*) AS 'Total'
    FROM
        appearance, actor
    WHERE
        appearance.ACT_ID = actor.ACT_ID
    GROUP BY appearance.ACT_ID
    ORDER BY Total DESC) AS Result;

This returns a single column of the name Total Appearances with a value of 9.

You can use RANK() window function:

SELECT
    ACT_FNAME AS 'First Name',
    ACT_LNAME AS 'Last Name',
    Total
FROM (
  SELECT 
      ac.ACT_FNAME,
      ac.ACT_LNAME,
      COUNT(*) AS 'Total',
      RANK() OVER ( ORDER BY COUNT(*) DESC) as 'rank'
  FROM appearance ap
      JOIN actor ac ON ap.ACT_ID = ac.ACT_ID
  GROUP BY ap.ACT_ID
) as q
WHERE rank=1

In older MySQL you could do:

SELECT 
  totals.ACT_FNAME  AS 'First Name',
  totals.ACT_LNAME AS 'Last Name', 
  totals.Total
FROM (
  SELECT 
      ac.ACT_FNAME,
      ac.ACT_LNAME,
      COUNT(*) AS 'Total'
  FROM appearance ap
    JOIN actor ac ON ap.ACT_ID = ac.ACT_ID
  GROUP BY ap.ACT_ID
) as totals
  JOIN (
    SELECT MAX(cnt) as MAX_CNT
    FROM (
      SELECT ACT_ID, COUNT(*) as 'cnt'
      FROM appearance 
      GROUP BY ACT_ID
    ) as q
  ) ap_max 
WHERE totals.Total=ap_max.MAX_CNT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM