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粉7187309562024-03-31 14:00:05
一種方法是使用帶有子查詢的左連接,它只傳回最大值。需要使用 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 ;
為了更容易理解,請執行下面的查詢,您將發現服務表中除值 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 ;
編輯。答案在 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 ;
P粉9365685332024-03-31 09:12:10
使用求和
:
select position, sum(experience = 100) from tbl group by position