2015-06-30 42 views
2

我有一个由查询组获取我的一些记录。如果我希望查找代表这些记录的其他列详情,该怎么办?选择查询以从内部查询的这些记录中选择列。内部查询和外部查询有不同的列

假设我有一个查询如下。 Select id,max(date) from records group by id; 以获取表格中最近的条目。 我希望获取另一列代表这些记录。

我想要做这样的事情(例如,这个不正确的查询): Select type from (Select id,max(date) from records group by id)但这里的类型不存在于内部查询中。

我无法以更简单的方式定义问题,我为此道歉。

任何帮助表示赞赏。

编辑:

Column |   Type   | Modifiers 
--------+-----------------------+----------- 
id  | integer    | 
rdate | date     | 
type | character varying(20) | 

样本数据:

id | rdate | type 
----+------------+------ 
    1 | 2013-11-03 | E1 
    1 | 2013-12-12 | E1 
    2 | 2013-12-12 | A3 
    3 | 2014-01-11 | B2 
    1 | 2014-01-15 | A1 
    4 | 2013-12-23 | C1 
    5 | 2014-01-05 | C 
    7 | 2013-12-20 | D 
    8 | 2013-12-20 | D 
    9 | 2013-12-23 | A1 

当我试图像这样(我在SQL没有好):select type from records as r1 inner join (Select id,max(rdate) from records group by id) r2 on r1.rdate = r2.rdate ;

select type from records as r1 ,(Select id,max(rdate) from records group by id) r2 inner join r1 on r1.rdate = r2.rdate ; 
+0

你可以发布你的表格定义和一些样品数据吗? – mlinth

回答

1

如果我理解了这个任务离子对的,那么这应该工作(或者至少给你的东西,你可以工作):

SELECT 
    b.id, b.maxdate, a.type 
FROM 
    records a -- this is the records table, where you'll get the type 
INNER JOIN -- now join it to the group by query 
    (select id, max(rdate) as maxdate FROM records GROUP BY id) b 
ON -- join on both rdate and id, otherwise you'll get lots of duplicates 
    b.id = a.id 
AND b.maxdate = a.rdate 

请注意,如果您有不同的类型相同的id和RDATE组合,你会得到重复记录。

+0

这正是我想要的而不是a和b,我有r1和r2,但在连接中它说列r2.rdate不存在。从记录中选择类型r1内部连接(从记录组中按id选择id,max(rdate))r2在r1.id = r2.id和r1.rdate = r2.rdate; –

+1

您需要通过查询在您的组中使用别名。这就是“as maxdate”在我的查询中所做的。例如从记录中选择类型r1内连接(选择id,max(rdate)为max_rdate from记录group by id)r2 on r1.id = r2.id and r1.rdate = r2.max_rdate – mlinth

+0

是否有拼写错误i.maxdate –

2

您可以轻松地用window function做到这一点:

SELECT id, rdate, type 
FROM (
    SELECT id, rdate, type, rank() OVER (PARTITION BY id ORDER BY rdate DESC) rnk 
    FROM records 
    WHERE rnk = 1 
) foo 
ORDER BY id; 

窗口定义OVER (PARTITION BY id ORDER BY rdate DESC)需要用相同的id值的所有记录,然后排序,然后从最新到最近期rdate并分配一个等级至每一行。 1的等级是最近的,等于max(rdate)

+0

我将不得不在postgresql上工作更多。我会查找它。 –