Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在sqlite中使用group by时,选择特定行的rowid_Sqlite_Group By - Fatal编程技术网

在sqlite中使用group by时,选择特定行的rowid

在sqlite中使用group by时,选择特定行的rowid,sqlite,group-by,Sqlite,Group By,我在SQLite中有一个查询,其中我按某一列分组,并在select语句的另一列上使用聚合函数MAX。现在,我还需要保存MAX aggregate显示的值的行的rowid。我知道这一定是一个唯一的行,因为主键约束。我不知道如何编写查询。请参见以下示例: create table t1 (c1, c2, constraint t1_pk primary key (c1, c2)); insert into t1 values ('boys', 1); insert into t1 values (

我在SQLite中有一个查询,其中我按某一列分组,并在select语句的另一列上使用聚合函数MAX。现在,我还需要保存MAX aggregate显示的值的行的rowid。我知道这一定是一个唯一的行,因为主键约束。我不知道如何编写查询。请参见以下示例:

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的最大值。然后我想要保存现在显示的值的行的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
使用最小聚合的第二个查询应该返回包含最小值的行的rowid,这就是我想要实现的:

rowid|c1|min(c2)
1|boys|1
3|girls|1
现在,我尝试了以下subselect,它也不起作用,因为它给出了一个错误:

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()

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

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

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;

检查

事实上,根据@Pradeeshnarayan的回答,我不得不对其进行改进,以使其在Oracle中工作。 “GROUPBY”子句是无用的

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

非常感谢,完美的解决方案!顺便说一句,我不知道小提琴,但它看起来真的很有趣,谢谢你的提示。