SQL group by和aggregate函数

时间:2015-06-02 21:22:14

标签: oracle

我有一个包含样本数据的下表结构(仅列出了感兴趣的列)。我希望查询返回由up_id的#完成的bsp_id的#。

bsp_id | up_id | status_flag
1256     15      completed
1232     1       completed
1216     15      completed
1216     1       completed
1235     1       completed

,查询结果应为

Count(bsp_id) | Count(up_id)
    1                 2
    3                 1 

2 个答案:

答案 0 :(得分:0)

如果您的意思如下,

Count(bsp_id) | Count(up_id)
    2                 1
    3                 1 

然后查询应该是:

select count(bsp_id), count(up_id) // count(up_id) will always be 1
from tbl
where status_flag = 'completed'
group by up_id

答案 1 :(得分:0)

您需要嵌套查询。这样的事情应该有效:

内部查询:

select bsd_id, count(*) as c from mitable
where status_flag='completed' group by bsd_id

结果:

1256,1

1232,1

1216,2

1235,1

完整的查询:

select count(*), t.c from
(select bsd_id, count(*) as c from mitable
where status_flag='completed' group by bsd_id) t
group by t.c

结果:

1,2

3,1