找到表中的最大值,然後分別顯示SQL組以及每個SQL組中最大值的數量
P粉451614834
P粉451614834 2024-03-30 15:53:50
0
2
370

ID  POSITION    EXPERIENCE  SALARY
1   top               90    1500
2   bottom           100    1500
3   top               90    750
4   left              90    1000
5   right            100    1300
6   top               90    1500
7   left              80    2000
8   top               80    1000
9   bottom           100    2000
10  left             100    2000

所以,這是我的表 SERVICE,其中(如我們所見)最大經驗是 100。 我需要編寫一個查詢來尋找透過位置(左、右、上、下)組成的每個組中經驗中出現 100 的次數。

所以我寫道:-

select position,count(*)
from service
group by position
having experience=(select max(experience) from service);

預期輸出:-

POSITION  COUNT(*)
bottom         2 
left           1
right          1
top            0

但是, 它給了我一個錯誤:-「不是 GROUP BY 表達式」

我的邏輯是,首先我將其分成幾組,然後使用having子句來計算每組中經驗等於最大值的元組。經驗。

P粉451614834
P粉451614834

全部回覆(2)
P粉718730956

一種方法是使用帶有子查詢的左連接,它只傳回最大值。需要使用 case 來傳回具有任意最大值的群組。

SELECT s.position,
       sum(case when max_experience is null then 0 else 1 end ) as max_count
FROM service s
LEFT JOIN  ( select max(experience) as max_experience
             from service 
            ) as s1 ON  s.experience = s1.max_experience
group by s.position
order by max_count desc ;

https://dbfiddle.uk/-8pHZ8wm

為了更容易理解,請執行下面的查詢,您將發現服務表中除值 100 之外的每一行中 max_experience 均為空。簡單來說,您只需要計算組中值為 100 和 0 的行還沒有達到最大經驗值。

SELECT s.*,s1.*
FROM service s
LEFT JOIN  (select max(experience) as max_experience
             from service 
            ) as s1 ON  s.experience = s1.max_experience ;

https://dbfiddle.uk/al8YYLk9

編輯。答案在 Oracle 中也有效,但需要刪除子查詢後面的關鍵字 as

SELECT s.position,
       sum(case when max_experience is null then 0 else 1 end ) as max_count
FROM service s
LEFT JOIN  ( select max(experience) as max_experience
             from service 
            )  s1 ON  s.experience = s1.max_experience
group by s.position
order by max_count desc ;

https://dbfiddle.uk/hhGB_xXx

P粉936568533

使用求和

select position, sum(experience = 100) from tbl group by position

參見小提琴

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!