Question

This query currently shows max(hella) so far

SELECT max(hella)
FROM (
SELECT G.firstname, G.lastname, count(*) as hella
FROM guest G, Timeslot TS, shows H
where G.timeslotnum = TS.timeslotnum
AND TS.shownumber = H.shownumber
AND H.showname = 'Fitness'
Group by g.firstname, G.lastname
ORDER by hella
)
As blabla

I want to show firstname and lastname of max(hella) entry

Was it helpful?

Solution

This is much like what @maniek or @zfus already posted: returns a single row, arbitrary pick if there are ties. But with proper JOIN syntax and shorter with some syntax candy:

SELECT g.firstname, g.lastname, count(*) AS hella
FROM   guest    g
JOIN   timeslot t USING (timeslotnum)
JOIN   shows    s USING (shownumber)
WHERE  s.showname = 'Fitness'
GROUP  BY 1,2
ORDER  BY 3 DESC
LIMIT  1;

SQL Fiddle (reusing @sgeddes' fiddle).

OTHER TIPS

SELECT G.firstname, G.lastname, count(*) as hella
FROM guest G, Timeslot TS, shows H
where G.timeslotnum = TS.timeslotnum
AND TS.shownumber = H.shownumber
AND H.showname = 'Fitness'
Group by g.firstname, G.lastname
ORDER by hella desc
limit 1

While SoulTrain and sgeddes have an answer from one angle, if your desire is to show only one record with the max count, you could simply write something like this:

SELECT G.firstname, G.lastname, count(*) as hella
FROM 
    guest G,
    Timeslot TS, 
    shows H
where 
    G.timeslotnum = TS.timeslotnum
    AND TS.shownumber = H.shownumber
    AND H.showname = 'Fitness'
Group by 
    g.firstname, 
    G.lastname
ORDER by 
    hella desc
fetch first 1 rows only

Example in SQLFiddle

Try this...

WITH CTE as
(
SELECT G.firstname, G.lastname, count(*)  as hella
FROM guest G, Timeslot TS, shows H
where G.timeslotnum = TS.timeslotnum
AND TS.shownumber = H.shownumber
AND H.showname = 'Fitness'
Group by g.firstname, G.lastname
)
SELECT firstname, lastname, hella
FROM CTE A
WHERE hella= (SELECT MAX(HELLA) FROM CTE B
WHERE A.firstname=B.firstname
and A.lastname=B.lastname)
As blabla

I'm not 100% sure I understand your question, but assuming you're looking for the first and last name of the person with the most record count, something like this should work:

with cte as (
  select g.firstname, g.lastname, count(*) cnt
  from guest g
      join timeslot ts on g.timeslotnum = ts.timeslotnum
      join shows s on ts.shownumber = s.shownumber and s.showname = 'Fitness'
  group by g.firstname, g.lastname
)
select firstname, lastname
from cte
where cnt = (select max(cnt) from cte);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top