创建Postgres交叉表查询并计算列之间的差异

时间:2013-12-05 14:15:08

标签: sql postgresql

Tni分析

我的数据格式为

Patid | TNT     | date
 A123 | 1.2.    | 23/1/2012
 A123 | 1.3.    | 23/1/2012
 B123 | 2.6.    | 24/7/2011
 B123 | 2.7.    | 24/7/2011

我希望能够像这样计算两行之间的差异

rowid. | TNT-1. | TNT-2. | difference
A123.  |. 1.2.  | 1.3.   | 0.1
B123.  | 2.6.   | 2.7.   | 0.1

Etc

我认为这是Postgres中交叉表功能的用途,但我很难获得结果。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以手动转动然后采取差异(假设每个Patid总共有2条记录,而您不必考虑date):

with cte1 as (
    select
        Patid, TNT, date, row_number() over(partition by Patid order by TNT) as rn
    from Table1
), cte2 as (
    select
        Patid,
        max(case when rn = 1 then TNT end) as "TNT-1",
        max(case when rn = 2 then TNT end) as "TNT-2"
    from cte1
    group by Patid
)
select
    Patid as rowid, "TNT-1", "TNT-2", "TNT-2" - "TNT-1" as difference
from cte2

-------------------------------------
ROWID    TNT-1    TNT-2    DIFFERENCE
A123       1.2      1.3           0.1
B123       2.6      2.7           0.1

<强> sql fiddle demo