SQL - 使用Count()添加列

时间:2016-06-10 18:05:25

标签: sql group-by common-table-expression

我想简单地在下面给出的结果中添加一个列,来自"选择计数(*)...按占有分组"。因此它仍应保留相同数量的行,并添加此列。我被告知要调查横向连接,但我不明白如何做到这一点,特别是在我的CTE查询的上下文中

QUERY

select
 *
 from (
       with possession_change as (
         select
           (lag(possession,1) over (order by id)) as last_possession,
           possession,
           clock
         from plays
         where
          game_id in (583615)
          and league = 3
          and period in (0,1)
         )
       select * from possession_change
      ) stuff
;

结果

last_possession | possession | clock 
-----------------+------------+-------
                 |          0 |  3600
               0 |          0 |  3600
               0 |          0 |  3600
               0 |          0 |  3600
               0 |          1 |  3561
               1 |          1 |  3561
               1 |          1 |  3561
               1 |          1 |  3449
               1 |          1 |  3449
               1 |          0 |  3396
               0 |          0 |  3396
               0 |          0 |  3396

期望的结果

last_possession | possession | clock | possession_count
-----------------+------------+-------
                 |          0 |  3600  | 7
               0 |          0 |  3600  | 7
               0 |          0 |  3600  | 7
               0 |          0 |  3600  | 7
               0 |          1 |  3561  | 5
               1 |          1 |  3561  | 5
               1 |          1 |  3561  | 5
               1 |          1 |  3449  | 5
               1 |          1 |  3449  | 5
               1 |          0 |  3396  | 7
               0 |          0 |  3396  | 7 
               0 |          0 |  3396  | 7

1 个答案:

答案 0 :(得分:2)

您可以使用count over

select
    lag(possession,1) over (order by id) as last_possession,
    possession,
    clock,
    count(*) over (partition by possession) cnt
from plays
where
    game_id in (583615)
    and league = 3
    and period in (0,1)