窗口函數(window function) over 與 partition 的使用
準備資料
1 | Drop TABLE #testTable |
原資料內容如下
1 | SELECT * FROM #testtable order by id; |
id | name | age |
---|---|---|
1 | Bill | 40 |
2 | Tom | 10 |
3 | Mary | 60 |
4 | Joe | 10 |
5 | Tim | 60 |
6 | Alice | 5 |
除了列出原本資料外,想每筆資料再多附加一行,列出該同年齡的人數
1 | select *, count(*) over (partition by age) cnt from #testTable order by id |
id | name | age | cnt |
---|---|---|---|
1 | Bill | 40 | 1 |
2 | Tom | 10 | 2 |
3 | Mary | 60 | 2 |
4 | Joe | 10 | 2 |
5 | Tim | 60 | 2 |
6 | Alice | 5 | 1 |