postgresql 我不知道如何在SQL上添加分组值

kmpatx3s  于 2023-01-30  发布在  PostgreSQL
关注(0)|答案(1)|浏览(145)

数据表:

| WINNER   | FOOT CLUB|
| -------- | --------   |
|     1    | Beşiktaş   |                 
|     2    | Beşiktaş   |                        
|     3    |Galatasaray |
|     4    |Galatasaray |
|     5    | Beşiktaş   |    
|     6    | Istanbul   |
|     7    | Istanbul   |
|     8    | Istanbul   |
|     9    |Galatasaray |
|    10    |Galatasaray |
|    11    |Fenerbahçe  |
|    12    |Fenerbahçe  |
|    13    |Fenerbahçe  |
|    14    | Istanbul   |

请帮帮忙。我需要一个相同值序列的排序数组出现。使用任何版本的SQL语法。我需要这个结果:

Beşiktaş    2
Galatasaray 2
Beşiktaş    1
Istanbul    3
Galatasaray 2
Fenerbahçe  3
Istanbul    1
CREATE TABLE football (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL
   );

INSERT INTO football VALUES (1, 'Beşiktaş');
INSERT INTO football VALUES (2, 'Beşiktaş');
INSERT INTO football VALUES (3, 'Galatasaray');
INSERT INTO football VALUES (4, 'Galatasaray');
INSERT INTO football VALUES (5, 'Beşiktaş');
INSERT INTO football VALUES (6, 'Istanbul');
INSERT INTO football VALUES (7, 'Istanbul');
INSERT INTO football VALUES (8, 'Istanbul');
INSERT INTO football VALUES (9, 'Galatasaray');
INSERT INTO football VALUES (10, 'Galatasaray');
INSERT INTO football VALUES (11, 'Fenerbahçe');
INSERT INTO football VALUES (12, 'Fenerbahçe');
INSERT INTO football VALUES (13, 'Fenerbahçe');
INSERT INTO football VALUES (14, 'Istanbul');

SELECT name, 
RANK() OVER() 
FROM football

结果是这样的:

Beşiktaş|1
Beşiktaş|1
Galatasaray|1
Galatasaray|1
Beşiktaş|1
Istanbul|1
Istanbul|1
Istanbul|1
Galatasaray|1
Galatasaray|1
Fenerbahçe|1
Fenerbahçe|1
Fenerbahçe|1
Istanbul|1
jchrr9hc

jchrr9hc1#

以下内容改编自this solution.
Dbfiddle for your solution if desired

select name, count(*) as cnt
from (select t.*,
             (row_number() over (order by id) - row_number() over (partition by name order by id)
             ) as grp
      from football t
     ) t
group by name, grp
order by min(id) asc

相关问题