Solved

SQL Update records with their occurance with a group

Posted on 2014-10-28
2
149 Views
Last Modified: 2014-10-29
I have a t-SQL problem I can't get my head around.  I have a table of orders with each order having a unique alpha OrderNo.  Each order is associated with a BaseOrder in a many to one relation ship (one baseorder can have multiple orders).

The issue I have is I need to update the table and set a column to indicate the count of the order within the associated base order.  The example below indicates what I am after.  Orders 10001, 10012, 10018 and 1001A are all associated with BaseOrder 10001.  I need to update the SubOrderNumber with 1, 2, 3, 4 respectively as I want them stamped in incremental order based on their alpha sort order.


Example
0
Comment
Question by:canuckconsulting
2 Comments
 
LVL 15

Accepted Solution

by:
Haris Djulic earned 500 total points
ID: 40409616
Firts try if this select is ginivng you required output :


select orderno, baseorder,  ROW_NUMBER() OVER (PARTITION BY orderno, baseorder ORDER By orderno, baseorder) as SubOrderNumber 
from orders

Open in new window

then try this:

UPDATE t
SET t.SubOrderNumber = t2.SubOrderNumber 
FROM order t
INNER JOIN (
select orderno, baseorder,  ROW_NUMBER() OVER (PARTITION BY orderno, baseorder ORDER By orderno, baseorder) as SubOrderNumber 
from orders
)t2
ON (t.OrderNo= t2.OrderNo and t.BaseOrder =t2.BaseOrder  )
WHERE conditions;

Open in new window

0
 

Author Closing Comment

by:canuckconsulting
ID: 40410996
Fabulous!  I had never heard of the over clause...what a handy tool!

Thanks,

Scott
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
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.
Viewers will learn how the fundamental information of how to create a table.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question