Mysql 仅使用一列序列的第一行进行分组?

Mysql 仅使用一列序列的第一行进行分组?,mysql,sql,group-by,Mysql,Sql,Group By,首先,这里是我想要的alpha版本: 但是,我不想计算所有代表性的id,而只计算id最低的这一行,例如: (`id`, `economy_id`, `representative_id`) (1, 1, 5), <-this one, lowest id through the same economy_id=1 (2, 1, 6), (3, 1, 7), (4, 1, 8), (5, 1, 3), (6, 1, 4), (7, 1, 1), (8, 1, 2), (9, 1, 102),

首先,这里是我想要的alpha版本:

但是,我不想计算所有代表性的id,而只计算id最低的这一行,例如:

(`id`, `economy_id`, `representative_id`)
(1, 1, 5), <-this one, lowest id through the same economy_id=1
(2, 1, 6),
(3, 1, 7),
(4, 1, 8),
(5, 1, 3),
(6, 1, 4),
(7, 1, 1),
(8, 1, 2),
(9, 1, 102),
(10, 2, 7), <-this one, lowest id through the same economy_id=2
(11, 2, 8),
(12, 2, 102),
(13, 2, 1),
(14, 2, 2),
(15, 2, 3),
(16, 2, 4),
(17, 3, 3), <-this one, lowest id through the same economy_id=3
(18, 3, 4),
(19, 3, 1),
(20, 3, 2),
(21, 3, 102),
(22, 4, 1), <-this one, lowest id through the same economy_id=4
(23, 4, 2),
(24, 4, 102),
(25, 5, 1),  <-this one, lowest id through the same economy_id=5
(26, 5, 2),
(27, 5, 102),
(28, 5, 7),
(29, 6, 1),  <-this one, lowest id through the same economy_id=6

只有在SQL中才有可能吗?

如果我正确理解了您的问题,我认为在
子查询中使用
min
并重新连接到自身,这应该是可行的:

select s.representative_id, count(*)
from stl_parliament s
  join 
  (
    select min(id) minid
    from stl_parliament
    group by economy_id
  ) t on s.id = t.minid
group by s.representative_id

你的问题有点让人困惑。 这是你想要的吗


有点复杂,但应该可以:

select m.col1, m.col2, count(m.col2) from (
select t.economy_id as col1, l.representative_id as col2 from stl_parliament l,
(select economy_id,MIN(id) as minid from stl_parliament GROUP BY economy_id) t
where t.economy_id=l.economy_id and t.minid=l.id) m group by m.col2

有很多子查询,我不太擅长连接

请尝试下面的查询

SELECT a.rep_id,count(a.rep_id) 
FROM(Select min(id) as mid,representative_id as rep_id,economy_id 
FROM stl_parliament 
GROUP BY economy_id) as a
GROUP BY a.rep_id

我不明白这是怎么回事count@Strawberry嗨,草莓:谢谢你在这里:)哪个算?有人更新了我的帖子,但现在是不正确的。怎么把它转回去@草莓这个计数意味着代表性id作为同一经济体id更新序列中的第一个记录(最低id)出现了多少次-我想我已经说得更清楚了-(我把它改回来了:)这不是什么明显的问题,太棒了!除了您所做的特殊计数、普通常规计数、代表性计数、常规计数、子查询计数之外,是否可以添加输出?还是在单独的查询中进行比较好?@RobM——太好了,我不是100%确定你需要什么,但很高兴这能奏效!
select count(economy_id), min_rep_id
from 
(
SELECT economy_id, min(representative_id) as min_rep_id
from stl_parliament
GROUP BY economy_id
) as x
GROUP BY min_rep_id
select m.col1, m.col2, count(m.col2) from (
select t.economy_id as col1, l.representative_id as col2 from stl_parliament l,
(select economy_id,MIN(id) as minid from stl_parliament GROUP BY economy_id) t
where t.economy_id=l.economy_id and t.minid=l.id) m group by m.col2
SELECT a.rep_id,count(a.rep_id) 
FROM(Select min(id) as mid,representative_id as rep_id,economy_id 
FROM stl_parliament 
GROUP BY economy_id) as a
GROUP BY a.rep_id