Grouping by or iterating through partitions in SQL

╄→гoц情女王★ 提交于 2019-12-02 14:29:31

问题


Two part question regarding partitioning in SQL.

In T-SQL when you use PARTITION BY is there a way to assign a unique number to each partition, in addition to something like row_number()?

E.g. row_number() would yield,

Action          Timestamp           RowNum
A               '2013-1-10'         1
A               '2013-1-11'         2
B               '2013-1-12'         1
B               '2013-1-13'         2

Whereas, in addition, uniquely identifying each partition could yield,

Action          Timestamp           RowNum          PartitionNum
A               '2013-1-10'         1               1
A               '2013-1-11'         2               1
B               '2013-1-12'         1               2
B               '2013-1-13'         2               2

Then one could GROUP BY partition number.

Second part of my question is, how can you break out each partition and iterate through it, e.g.,

for each partition p
   for each row r in p 
       do F(r) 

Any way in T-SQL?


回答1:


You could use dense_rank():

select  *
,       row_number() over (partition by Action order by Timestamp) as RowNum
,       dense_rank() over (order by Action) as PartitionNum
from    YourTable

Example at SQL Fiddle.

T-SQL is not good at iterating, but if you really have to, check out cursors.



来源:https://stackoverflow.com/questions/16660169/grouping-by-or-iterating-through-partitions-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!