TSql Return Column Based on Partitions and Numbers

I have a SQL server table where I am trying to get a calculated column - MyPartition - indicates the section number based on the @segment variable. For example, if @segment = 3, then the following result will be indicated.

RowID  | RowName    | MyPartition
------ | -----------| -------
1      | My Prod 1  | 1
2      | My Prod 2  | 1
3      | My Prod 3  | 1
4      | My Prod 4  | 2
5      | My Prod 5  | 2
6      | My Prod 6  | 2
7      | My Prod 7  | 3
8      | My Prod 8  | 3
9      | My Prod 9  | 3
10     | My Prod 10 | 4

What I have so far looks something like this:

SELECT 
    RowId,
    RowName,
    ROW_NUMBER() OVER(PARTITION BY RowId ORDER BY RowId ASC) AS MyPartition
FROM MyTable
ORDER BY RowId

But since you can guess that the partition simply splits into rowid, giving all the values ​​mypartition = 1. I'm not sure how to structure the partition by clause to achieve this.

+4
source share
1 answer

What about

CEILING(ROW_NUMBER() OVER(ORDER BY RowId ASC) / 3.0)
+5
source

Source: https://habr.com/ru/post/1685540/


All Articles