mysql分組后如何獲取每個組的第一條數(shù)據(jù)
mysql分組后獲取每個組的第一條數(shù)據(jù)
已知:subject表(主題表),主題表為樹形表
path字段,使用分隔符###,將主題編碼從一級到本級主題編碼,拼接起來,便于查詢主題下子主題數(shù)據(jù)。
現(xiàn)在,需要根據(jù)path排序,聚合查詢一級主題的名稱和條數(shù)。
直接上結果:
兩種寫法:
一:內(nèi)層distinct
select tt.name as subjectName,path,count(*) as countNum from ?(select **distinct t.table_id_**, t.SUBJECT_ID_, s.name_ as name,path_,SUBSTRING_INDEX(path_,'###',1) as path from model_table t ?join hdgp_standard_subject s on t.SUBJECT_ID_ = s.id_ where t.IS_DELETE_ = 0 and !isnull(t.SUBJECT_ID_) and t.VERSION_TYPE_ = 'formal' order by s.path_ ?) tt group by tt.path ;
二:內(nèi)層group
select tt.name as subjectName,path,count(*) as countNum from ?(select t.SUBJECT_ID_, s.name_ as name,path_,SUBSTRING_INDEX(path_,'###',1) as path from model_table t ?join hdgp_standard_subject s on t.SUBJECT_ID_ = s.id_ where t.IS_DELETE_ = 0 and !isnull(t.SUBJECT_ID_) and t.VERSION_TYPE_ = 'formal' **group by t.table_id_** order by s.path_ ?) tt group by tt.path ;
解釋一下:
直接查詢是查不出想要的結果的,需要嵌套子查詢。但是只嵌套只查詢也是有問題的,內(nèi)層循環(huán)也需要進行過濾一下,可以使用distinct或者group ,再聯(lián)合order by 進行排序,才能獲取想要的結果。
這樣寫,發(fā)現(xiàn)一個問題,就是如果只有子主題的話,就查不出來一級主題了,改進如下:(多關聯(lián)一遍,這樣子查詢都省了)
SELECT ? ? ss.NAME_ AS subjectName, ? ? count(*) AS countNum FROM ? ? model_table t ? ? ? ? JOIN hdgp_standard_subject s ON t.SUBJECT_ID_ = s.id_ ? ? ? ? JOIN hdgp_standard_subject ss ON SUBSTRING_INDEX( s.path_, '###', 1 ) = ss.CODE_ WHERE ? ? t.IS_DELETE_ = 0 ? AND ! isnull( t.SUBJECT_ID_ ) ? AND t.VERSION_TYPE_ = 'formal' GROUP BY ? ? ss.code_
mysql獲取每組的第二條記錄
-- rank 第n次重復, last_patient表中某一重復字段名稱 SELECT t.id,t.patient_id,t.patient_name FROM ( select id,patient_id,patient_name, if(@last_patient = a.patient_id,@rank := @rank+1,@rank := 1) AS "rank", -- 判斷 當前patient_id與@last_patient是否相等,不相等rank為1,相等時rank加1, @last_patient := a.patient_id FROM lis_data_collection a,(SELECT @rank:=0,@last_patient:="") r -- 聲明兩個變量@rnak及@last_patient,并初始化 ORDER BY a.id asc ) t where rank= 2 ORDER BY id ASC
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
MYSQL 5.6 從庫復制的部署和監(jiān)控的實現(xiàn)
這篇文章主要介紹了MYSQL 5.6 從庫復制的部署和監(jiān)控的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12
mysql如何刪除數(shù)據(jù)表和關聯(lián)的數(shù)據(jù)表刪除詳情
這篇文章主要介紹了mysql如何刪除數(shù)據(jù)表和關聯(lián)的數(shù)據(jù)表刪除詳情,刪除數(shù)據(jù)表的時候,表的定義和表中所有的數(shù)據(jù)均會被刪除。因此,在進行刪除操作前,最好對表中的數(shù)據(jù)做一個備份,以免造成無法挽回的后果2022-07-07
mysql中GROUP_CONCAT函數(shù)使用技巧及問題詳解
這篇文章主要給大家介紹了關于mysql中GROUP_CONCAT函數(shù)使用技巧及問題的相關資料,GROUP_CONCAT是MySQL中的一個聚合函數(shù),它用于將多行數(shù)據(jù)按照指定的順序連接成一個字符串并返回結果,需要的朋友可以參考下2023-11-11

