Postgresql:从同一个表中查询

时间:2016-09-27 12:54:34

标签: postgresql

我有一张桌子:

id1  |  date     |  idreff |
A11  | 2015-01-01| A11
B12  | 2016-02-03| A11
C53  | 2016-05-26| A11

ID1有一个IDreff。我想从日期中提取两种年龄: 1.交易年龄本身 2.第一笔交易的年龄,基于IDreff。

所以,我想要这个结果:

id1  |  date     |  idreff | Age of Transaction | Age IDreff

A11  | 2015-01-01| A11    
B12  | 2016-02-03| A11    
C53  | 2016-05-26| A11

如何在同一查询中获得两个查询(事务ID1和IDreff的年龄)的结果?

我试过这个:

SELECT *, age(t1.date) AS age1, age(t2.date) FROM table t1, table t2 WHERE t1.idreff=t2.id1

但结果并非如此,因为每行给我两倍。

2 个答案:

答案 0 :(得分:0)

您可以像这样修改您的SQL:

SELECT 
    t1.*, age(t1.date) AS age1, age(t1.date, t2.date) 
FROM 
    table t1, table t2 
WHERE 
    t1.idreff=t2.id1

答案 1 :(得分:0)

你应该写更精确的连接:

SELECT 
    *, 
    age(t1.date) AS age1, 
    age(COALESCE(t2.date,t1.date)) as base_age
FROM 
    table t1
LEFT JOIN table t2 ON (t1.idreff=t2.id1 AND t1.id1<>t2.id1)
WHERE 1 = 1