sql group by group query maximum data

method one:

Use group by and order by in mysql to take the largest row of data in each group

SELECT t.*
FROM (select * from `monitor_company_event` order by `create_time` desc limit 10000000000) t
GROUP BY t.company_name,t.row_key,t.event_subType

 My practice:

define query ad_query(@BEGIN date,@END date)
begin

SELECT
	q.unitid,m.stdname,g.GGZB_DJLX,g.GGZB_TJLS,q.datatime,q.cq_statetime
FROM
	CQ_PROJECT_INFO AS q
        JOIN md_org as m on q.unitid = m.objectid
	JOIN ggzb AS g ON  g.unitid  =  q.unitid  AND g.datatime = q.datatime 
WHERE
	to_char ( q.cq_defineflow_id ) = 'AA802EA09C93F879BA52CBC6877DC7D1' 
        AND q.cq_statetime between @BEGIN and @END
        AND q.cq_currnodetitle = '结束'
	AND g.ggzb_tjls IS NOT NULL 
union
select A.unitid,A.stdname,A.GGZB_DJLX,A.GGZB_TJLS,A.datatime,A.finishtime
FROM
(SELECT
	c.unitid,m.stdname,c.datatime,g.GGZB_DJLX,g.GGZB_TJLS,n.finishtime
FROM
	CQ_PROJECT_INFO AS c
        JOIN processinstance AS p ON to_char ( c.recid ) = to_char ( p.workref )
	JOIN nodeinstance AS n ON to_char ( n.piguid ) = to_char ( p.recid ) 
        LEFT JOIN md_org as m on m.objectid = c.unitid  #若用 JOIN 则慢了有6/7s
        JOIN ggzb AS g ON  g.unitid  =  c.unitid  AND g.datatime = c.datatime
WHERE
	to_char ( c.cq_defineflow_id ) = 'AA802EA09C93F879BA52CBC6877DC7D1' 
	AND n.nodename = 'MANUAL4' AND n.finishtime is not null AND n.finishtime between @BEGIN and @END order by n.finishtime desc
)AS A group by to_char(A.unitid),A.datatime

end

 

Method Two:

Other blog post examples

select a.id,a.z,a.u_id from show_video a inner join (select u_id,max(z) score from show_video group by u_id)b on a.
u_id=b.u_id and a.z = b.score GROUP BY u_id

 

Guess you like

Origin blog.csdn.net/xiangwang2016/article/details/104455576