Solved

Sequential number grouped by Ordernumber

Posted on 2016-10-12
35 Views
Hello,

I'm trying to generate a column in a SQL Server 2008 query  where I can have a sequential number for all the order records that include their order details.  I basically want to have a sequential number grouped by order number, which can be repeated if the order has multiple rows.

In this case, the first row is what I need.

MySq      Ord#      Product            OrdDetailSeq
1      42825      widget1            1
2      42828      widget3            1
3      42829      widget1            1
3      42829      widget2            2
3      42829      widget4            3
4      42832      widget2            1
4      42832      widget3            2
5      42837      widget2            1

Does anyone know how to accomplish this?

Thanks.
0
Question by:TheUndecider
• 3

LVL 69

Assisted Solution

ScottPletcher earned 200 total points
ID: 41840358
SELECT MySq,      Ord#,      Product,
ROW_NUMBER() OVER(PARTITION BY Ord# ORDER BY Product) AS OrdDetailSeq
FROM ...
0

LVL 65

Expert Comment

ID: 41840364
Not sure what 'In this case, the first row is what I need.' means, but looking at the desired set and the rest of the description OrdDetailSeq can be generated using ROW_NUMBER:
``````SELECT MySq, [Ord#], Product,
ROW_NUMBER() OVER (PARTITION BY [Ord#] ORDER BY Product) as OrdDetailSeq
FROM YourTable
``````
0

Author Comment

ID: 41840954
Thank you for replying, but what I need is the first column: MySq.  The rest of the columns are already there.  I need the sequential number for each set of rows that share the same order number.
0

LVL 65

Accepted Solution

Jim Horn earned 300 total points
ID: 41840962
>Thank you for replying, but what I need is the first column: MySq.
Your question said 'first row', which confused everyone.  Try this
``````SELECT
RANK() OVER (ORDER BY [Ord#]) as MySq,
[Ord#], Product, OrdDetailSeq
FROM YourTable
``````
0

LVL 65

Expert Comment

ID: 41842026
Thanks for the split.  Good luck with your project.  -Jim
0

Featured Post

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be \$37.1B.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…