每组的结果

时间:2011-08-16 15:42:36

标签: sql postgresql group-by

更新:

在is_active = false之后可以有is_active = true,所以我需要获取最后指定的is_active = true并获取前面的is_active = false记录

我有一个具有这种结构的表

id (not pk but each group is incremental), name, grp, is_active (boolean)

使用类似于第1组的数据

1, name1, group1, true
2, name2, group1, true
3, name3, group1, false
4, name1, group1, false
5, name2, group1, true
6, name3, group1, false <-- this is the next assigned id as the preceding record has an is_active = true
7, (names will differt, group the same and all false)...

...同一个表中的更多数据,但是对于group2

100, name1, group1, true
101, name2, group1, true
102, name3, group1, true
103, name1, group1, true
104, name2, group1, true
105, name3, group1, false <-- this is the next assigned id as the preceding record has an is_active = true
106, (names will differt, group the same and all false)...

我有这个,但它没有像我希望的那样工作

SELECT grp, COUNT(*)
FROM tbl_1
WHERE is_active = false
AND id > (
    SELECT id
    FROM tbl_1
    WHERE is_active = true
    ORDER BY id DESC
    LIMIT 1
)
GROUP BY grp

所以我想要的回报是:

group1, 6
group2, 105

但我只得到

group2, 105

3 个答案:

答案 0 :(得分:3)

您只需找到第idis_active = false。没有必要在id上应用“大于第一个有效”条件。

SELECT MIN(id), grp
  FROM tbl_1
  WHERE is_active = false
  GROUP BY grp

<强>更新

回答更新后的问题:

SELECT min(id), grp
  FROM tbl_1 t
  WHERE is_active = false
  AND id > (SELECT max(id) 
              FROM tbl_1 
              WHERE is_active = true 
                AND grp = t.grp)
  GROUP BY grp;

答案 1 :(得分:2)

SELECT grp, MIN(id) FROM tbl_1 WHERE is_active = false GROUP BY grp;

答案 2 :(得分:2)

SELECT 
grp,
MIN(Id)
FROM tbl_1
WHERE is_active = false 
GROUP BY grp