获取正确的数据 - 城市和省份数量

时间:2015-02-08 08:37:34

标签: sql postgresql select get

表的结构:

ID | firm | city | province

1  | test1 | Warszawa | 1
2  | test2 | Gdańsk   | 12
3  | test3 | Otwock   | 1
3  | test4 | Kraków   | 3
4  | test5 | Olkusz   | 3

这是我的SQL查询:

    SELECT COUNT(miasto) AS cntcity, wojewodztwo, miasto FROM tabela GROUP BY wojewodztwo, miasto ORDER BY wojewodztwo

结果是:

cnt_city | province   | city
6           1           Warszawa
2           1           Otwock
3           5           Kraków
7           5           Olkusz
3           12          Gdańsk  

我想要数" cnt_city"太,或者更确切地说是SUM" cnt_city" - 6 + 2 = 8,3 + 7 = 10,3我知道如何在PHP中执行此操作,但是可以在SQL中执行此操作吗?如何修改上面的SQL查询? 我想要这样的结果:

cnt_city | province | city      | cnt_firm
6          1           Warszawa | 8
2          1           Otwock   | 8
3          5           Kraków   | 10
7          5           Olkusz   | 10
3          12          Gdańsk   | 3

1 个答案:

答案 0 :(得分:0)

使用Window Function

SELECT cntcity,
       province,
       city,
       Sum(cntcity)OVER(partition BY province) As cnt_firm
FROM   (SELECT Count(miasto) AS cntcity,
               province,
               city          to
        FROM   tabela
        GROUP  BY wojewodztwo,
                  miasto) a