可以获得我想要的记录集,寻找建议

时间:2011-07-26 13:58:17

标签: sql postgresql group-by

表格布局

id, inactive (Boolean), name
12500, f, foo
12345, f, foo
12344, f, foo
12343, f, foo
12342, t, foo
12..., t, foo (more records)
12200, f, bar
12005, f, bar
12004, f, bar
12003, f, bar
12002, t, bar
12..., t, bar (more records)
..............(more records with different names)

结果:

  • 需要按名称分组
  • 只需要非活动= f
  • 需要拳头无效= f,id
  • 需要计算每组的记录数,无效= f

因此,从上面的示例数据中我得到的结果集为:

id, inactive (Boolean), name, count
12343, f, foo, 157
12003, f, bar, 197
............. (any other names that fall into the above constraints)

任何正确方向的帮助都会很棒

1 个答案:

答案 0 :(得分:1)

select min (id), inactive, name, count(*) from tabke where inactive = 'f' group by inactive, name

编辑:

select b.minid, a.inactive, a.name, a.cnt from
(select inactive, name, count(*) cnt from table where inactive = 'f' group by inactive, name) a,
(select inactive, name, min(id) minid from table where inactive = 'f' group by inactive, name) b
where a.inactive = b.inactive and a.name = b.name