GROUP BY只有一列的第一行序列?

时间:2014-01-31 19:00:00

标签: mysql sql group-by

首先是我想要的alpha版本:http://sqlfiddle.com/#!2/45c89/2

但是我不想计算所有代表性的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

输出应为:

representative_id,count()

根据以上例子:

5, 1
7, 1
3, 1
1, 3

只能在SQL中使用吗?

5 个答案:

答案 0 :(得分:2)

如果我正确理解您的问题,我认为这应该可以在min中使用subquery并加入自身:

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

答案 1 :(得分:2)

SELECT x.representative_id
     , COUNT(*) total
  FROM stl_parliament x
  JOIN 
     ( SELECT economy_id
            , MIN(id) min_id 
         FROM stl_parliament
        GROUP
           BY economy_id
     ) y
    ON y.economy_id = x.economy_id 
   AND y.min_id = x.id
 GROUP 
    BY representative_id;

http://sqlfiddle.com/#!2/45c89/34

答案 2 :(得分:0)

你的问题有点令人困惑。 你想要的是什么?

http://sqlfiddle.com/#!2/a58c7/19

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

答案 3 :(得分:0)

有点复杂但应该有效:

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

很多子查询,我对连接不太好

答案 4 :(得分:0)

请尝试以下查询。

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