如何从列中的行中获得差异

时间:2016-06-27 05:51:00

标签: sql postgresql

所以我有这个问题:

select  sum( case when gender = 'Male'
        then 1 else 0 end )    as male 
from tbl_person

会产生这样的结果:

+------+
| male |
+------+
|    2 |
|    5 |
|   10 |
+------+

我想要的是在它旁边有一个列,它将显示每行的不同之处,如下所示:

+------+-----+
| male | gap |
+------+-----+
|    2 |     |
|    5 |   3 |
|   10 |   5 |
+------+-----+

我试过像How to get difference between two rows for a column field?这样的答案 但他们似乎没有工作。我认为它是因为该列是Sum()的结果。

1 个答案:

答案 0 :(得分:1)

使用LAG窗口功能

SELECT Male,
       COALESCE(Male - Lag(male)OVER(ORDER BY male), 0) AS gap
FROM   (SELECT Sum(CASE WHEN gender = 'Male' THEN 1 ELSE 0 END) AS male
        FROM   tbl_person) A