从子查询中选择不同顺序的列

时间:2013-01-14 06:23:05

标签: sql oracle

我有以下表格结构。我想根据具有最新login_datetime的office_id选择不同的user_id。

tbl_id      user_id     office_id login_datetime
----------------------------------------
1           2           28          12/28/2012 5:35:50 AM
2           2           15          12/28/2012 5:35:50 AM
3           3           20          12/28/2012 5:35:50 AM
4           4           28          12/28/2012 5:35:50 AM
5           2           28          12/28/2012 5:35:50 AM
6           4           15          12/28/2012 5:35:50 AM
7           3           20          12/28/2012 5:35:50 AM

我试过了:

SELECT user_id as u_id,office_id,
(select login_datetime from tbl t2 where t2.user_id=u_id AND ROWNUM=1 ORDER BY t2.tbl_id DESC ) as LAST_LOGIN  
FROM tbl
GROUP BY user_id,office_id

但是,它不适合我,任何帮助?

3 个答案:

答案 0 :(得分:3)

使用Window Function

SELECT  tbl_id, user_id, office_id,login_datetime
FROM    
    (
        SELECT tbl_id, user_id, office_id,login_datetime,
                ROW_NUMBER() OVER (PARTITION BY user_id, "office_id"
                                    ORDER BY login_datetime DESC) rn
        FROM tableName
    ) a
WHERE   a.rn = 1

答案 1 :(得分:2)

另一个解决方案是带有group by的直接keep dense rank

select user_id, office_id, 
 max(login_datetime) keep (dense_rank first order by login_datetime desc) as latest_login_datetime
from tbl
group by user_id, office_id 

或者如果您想要唯一的用户ID:

select user_id, 
 max(office_id)  keep (dense_rank first order by login_datetime desc) as lastest_office_id, 
 max(login_datetime) keep (dense_rank first order by login_datetime desc) as latest_login_datetime
from tbl
group by user_id

答案 2 :(得分:0)

好的,我已将示例更改为ORACLE

我将解释查询

首先,我选择了一个独特的user_id和office id(所以如果用户属于两个办公室,他将返回两次) 然后使用MAX login_datetime获取最新的日期时间,

然后在WHERE中我通过office_id过滤查询,其中它与所有不同的办公室相等。 (基本上我正在返回一个不同的office_id表)

最后,由于MAX功能,我按user_id和office_id进行分组

SELECT 
DISTINCT "user_id" ,
"office_id",
 MAX("login_datetime")
FROM TableName
WHERE "office_id" IN (SELECT DISTINCT "office_id" FROM TableName)
GROUP BY 
  "user_id",
  "office_id"

SQL Fiddle example