在sql中解决“不是单个组函数”的问题?

时间:2018-03-15 10:19:48

标签: sql oracle

我有一张这样的表

ID |  UserID |  Time   |
3     9200    10/12/2016
2     9200    11/12/2016
1     9200    13/12/2016
4     1000    01/10/2017
5     1000    03/10/2017

现在我想选择用户ID的最短日期 即,

userID      Time
9200        10/12/2016
1000        01/10/2017

我正在使用它,但它会抛出“不是表达式组”或“不是单个组表达式”

 select user_id, min(time) as earliest_date 
 from table
 where doc_id in (select doc_id from docs where description='some doc')

有什么工作吗? 除了选择rownum = 1

之外的地方

2 个答案:

答案 0 :(得分:2)

只需使用group by

select user_id, min(time) as earliest_date 
from table
group by user_id;

如果您希望整个行的时间最短,请使用分析函数:

select t.*
from (select t.*,  min(time) over (partition by user_id) as mintime from t) t
where time = mintime;

如果您想要每行min()

select t.*, min(time) over (partition by user_id)
from t;

答案 1 :(得分:0)

 select user_id, min(time) as earliest_date 
 from table
 where doc_id in (select doc_id from docs where description='some doc')
group by user_id

除了聚合列之外,您必须使用组中SELECT语句中提到的所有列。

相关问题