2014-03-29 209 views
1

該查詢目前顯示MAX(海拉)到目前爲止SQL顯示信息

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 

我想展示最大的名字和姓氏(海拉)項

+0

你想要所有的關係爲最大,或只有一個(任意)? –

回答

1

這很像@maniek或@zfus已發佈的內容:返回單行,如果有關係,則返回任意選擇。 但適當的JOIN語法和更短一些語法糖:

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(重用@sgeddes'小提琴)。

+0

謝謝!如果我正確地理解了這一點,我們按照降序排列,然後採用第一個邏輯上是最大的條目,我正確嗎? – user3241846

+1

是的,你知道了@ user3241846。如果約翰史密斯和馬克斯泰勒的計數都是45(這是最大計數),那麼使用限制1或只提取第一行的答案的一些答案的危險是,只有一個會顯示出來。 – zedfoxus

0

試試這個...

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 
0

我不是100%肯定我明白你的問題,但假設你正在尋找最記錄計數的人的姓和名,這樣的事情應該工作:

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); 
+1

最佳答案,假設OP想要潛在的關係...另外更喜歡加入語法... – user2480596

1
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 
1

雖然SoulTrain和sgeddes有從一個角度回答,如果你的願望是,以示與最大計數只有一條記錄,你可以簡單地寫這樣的事情:

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

+0

感謝您的幫助! – user3241846

+0

非常歡迎您! – zedfoxus