在sqlite中使用group by时选择某行的rowid

时间:2012-09-12 10:11:56

标签: sqlite group-by

我在SQLite中有一个查询,我按特定列分组,并在select语句的另一列上使用聚合函数MAX。现在我还想要行的rowid,它包含MAX聚合显示的值。我知道由于主键约束,这必须是唯一的行。我无法弄清楚如何编写查询。请参阅以下示例:

create table t1 (c1, c2, constraint t1_pk primary key (c1, c2));

insert into t1 values ('boys', 1);
insert into t1 values ('boys', 2);
insert into t1 values ('girls', 1);
insert into t1 values ('girls', 2);

现在,我在两个列上都有主要约束的表。表的SELECT查询提供以下输出:

sqlite> select rowid, * from t1;

rowid|c1|c2
1|boys|1
2|boys|2
3|girls|1
4|girls|2

现在我想按c1分组并选择c2的MAX。然后我想要行的rowid,它保存现在显示的值。请参阅以下查询:

sqlite> select rowid, c1, max(c2) from t1 group by c1;

rowid|c1|max(c2)
2|boys|2
4|girls|2

sqlite> select rowid, c1, min(c2) from t1 group by c1;

rowid|c1|min(c2)
2|boys|1
4|girls|1

使用MIN聚合的第二个查询应该返回包含MIN值的行的rowid,这是我想要实现的:

rowid|c1|min(c2)
1|boys|1
3|girls|1

现在我尝试了以下子选项,它不起作用,因为它给出了一个错误:

sqlite> select (select rowid from t1 b where b.c1 = a.c1 and b.c2 = max(a.c2)), a.c1, max(a.c2) from t1 a group by a.c1;

Error: misuse of aggregate function max()

sqlite> select (select rowid from t1 b where b.c1 = a.c1 and b.c2 = min(a.c2)), a.c1, min(a.c2) from t1 a group by a.c1;

Error: misuse of aggregate function min()

我尝试的最后一件事是FROM子句中的子查询,它也不起作用:

sqlite> select
   ...>         (select rowid from t1 b where b.c1 = c.c1 and b.c2 = c.c2),
   ...>         c1,
   ...>         c2
   ...> from
   ...>         (select a.c1, max(a.c2) as c2 from t1 a group by a.c1) c;

Error: misuse of aggregate: max()

sqlite> select
   ...>         (select rowid from t1 b where b.c1 = c.c1 and b.c2 = max(c.c2)),
   ...>         c.c1,
   ...>         max(c.c2)
   ...> from
   ...>         (select a.c1, a.c2 from t1 a group by a.c1) c;

Error: misuse of aggregate function max()

我的问题有解决办法吗?我真的不知道还能尝试什么。

2 个答案:

答案 0 :(得分:3)

如果我理解你的问题,请尝试这样:

select rowid, c1, min(c2) from t1 a
where c2=(select min(c2) from t1 b where b.c1=a.c1) 
group by rowid,c1;

检查FIDDLE

答案 1 :(得分:0)

的确,按照@Pradeeshnarayan的回答,我不得不改进它以使其在Oracle中工作。 “分组依据”子句没有用

select rowid, c1, c2 from t1 a
where c2=(select min(c2) from t1 b where b.c1=a.c1);