我可以获得按section_mod_id
分组的最高totalColumns数量查询
SELECT
day_id, section_mod_id, count(day_id) as totalColumns
FROM
`supervision` sup
INNER JOIN
`section_mod` s ON sup.section = s.section_mod_id
GROUP BY
day_id, section_mod_id
ORDER BY
(s.section_mod_id) ASC
例如
day_id section_mod_id totalColumns
-----------------------------------
127 2 3
103 2 1
23 2 2
105 2 1
23 6 1
到这个
day_id section_mod_id totalColumns
-----------------------------------
127 2 3
23 6 1
仅返回每个部分的最高编号
是否可以使用mysql数据库?
答案 0 :(得分:1)
在大多数数据库中,您可以使用ANSI标准row_number()
函数:
SELECT sm.*
FROM (SELECT day_id, section_mod_id, count(*) as totalColumns,
ROW_NUMBER() OVER (PARTITION BY section_mod_id ORDER BY count(*) DESC) as seqnum
FROM supervision s INNER JOIN
section_mod m ON s.section = m.section_mod_id
GROUP BY day_id, section_mod_id
) sm
WHERE seqnum = 1;
在MySQL中,最简单的方法可能是这个技巧:
SELECT SUBSTRING_INDEX(GROUP_CONCAT(day_id ORDER BY totalColumns DESC), ',', 1) as day_id,
section_mod_id, MAX(totalColumns)
FROM (SELECT day_id, section_mod_id, count(*) as totalColumns
FROM supervision s INNER JOIN
section_mod m ON s.section = m.section_mod_id
GROUP BY day_id, section_mod_id
) sm
WHERE seqnum = 1
GROUP BY section_mod_id
答案 1 :(得分:1)
使用子查询尝试以下内容。
注意:您可以使用临时表作为内部子查询。
select day_id,section_mod_id,totalColumns from
(
select t1.day_id ,t1.section_mod_id,t1.totalColumns
,count(*) as rowNumber
from
(SELECT day_id, section_mod_id, count(day_id) as totalColumns FROM supervision sup
INNER JOIN section_mod s ON sup.section = s.section_mod_id GROUP BY day_id, section_mod_id
) t1
inner join
(SELECT day_id, section_mod_id, count(day_id) as totalColumns FROM supervision sup
INNER JOIN section_mod s ON sup.section = s.section_mod_id GROUP BY day_id, section_mod_id
)t2
on t1.section_mod_id=t2.section_mod_id
and t1.totalColumns<=t2.totalColumns
group by t1.day_id, t1.section_mod_id,t1.totalColumns
) t where rowNumber=1