【问题标题】:Can get the record set I want, Looking for advice能拿到我想要的记录集,求指教
【发布时间】:2011-07-26 13:58:17
【问题描述】:

表格布局

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)

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

【问题讨论】:

  • 第一个建议:写一条sql语句。然后当它不起作用时,寻求帮助。
  • 感谢 Randy 的建议,事实上,我确实写了几个查询,但没有达到我想要的效果。因此我提出了这个问题。我认为让某人查看所需结果而不是我的查询会更容易

标签: sql postgresql group-by


【解决方案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

【讨论】:

  • 谢谢,我以为我需要在群组中添加更多内容,但您的第一个解决方案效果很好
猜你喜欢
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
  • 1970-01-01
相关资源
最近更新 更多