Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

SQL Server Query Syntax

Posted on 2011-02-21
14
Medium Priority
?
397 Views
Last Modified: 2012-05-11
I have a table that I append to every week with the latest weeks worth of data. I have a field called Region that once in a while gets changed to a new Region. So depending on the latest weeks data I need to update ALL the other values, for a StoreID, where the Regions are different. For example

Data in table
StoreID    Region     Week
1                NE          1
2                MW         1
3                SW         1

New Data adding to the table
StoreID     Region    Week
1               NW           2
2               MW           2
3               SE             2

Now the table looks like this
StoreID    Region     Week
1                NE            1
2                MW          1
3                SW           1
1                NW           2
2                MW           2
3                SE             2

After I add the new data to the table I need to update the Regions with the latest weeks data. So, StoreID 1 - Region should be updated to NW and for StoreID 3- Region should be updated to SE. How would I go about updating all the regions to the last weeks Region? Any help would be appreciated!!
0
Comment
Question by:johnnyaction
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 4
  • 2
14 Comments
 
LVL 1

Expert Comment

by:gparrish
ID: 34945844
This is just a stab, but could you do this, how predictive is your data?

1. Add a column for date/time like a timestamp
2. Select the Region (or any fields needed) from top 3 rows ordered descending based on timestamp.
3. Collect that select into a subquesry and update other rows or all rows as needed.

UPDATE Table
SET Region = ( SELECT top 1 Region from table where StoreID = 1 order by timestamp DESC)
WHERE StoreID=1


HTH,
greg
0
 
LVL 1

Author Comment

by:johnnyaction
ID: 34945868
Couldnt I do it on the Max(Week) somehow? Id like to be able to just update all the Regions based on the 'last' weeks Region value?

0
 
LVL 1

Expert Comment

by:gparrish
ID: 34945935
Yes you could, good idea!

select top 1 from Table where StoreID=1 order by Week DESC.

There is likely an easier way to get them all also, would need some testing.

select top 3 from Table where StoreID in (1,2,3) order by Week DESC.

and then....

select top 3 from Table where StoreID in (1,2,3) order by Week DESC.

UPDATE Table TBLU
SET Region = (select top 3 from Table TBLS where StoreID in (1,2,3) order by Week DESC.)
WHERE TBLU.StoreID=TBLS.StoreID

Copy that to a TEMP table and test it first of course!

-greg


0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 1

Author Comment

by:johnnyaction
ID: 34946045
I appreciate your help with this but there has to be a better way of updating these values. I would rather use MAX(Week) instead of worrying about using order by desc because when I add the data every week I just want to be able to run an update on all the data and if there is a change then have it updated. Thanks again
0
 
LVL 41

Expert Comment

by:Sharath
ID: 34946144
try this.
;with cte as (
select *,
       ROW_NUMBER() over (partition by StoreID order by [Week] desc) rn,
       MAX([Week]) over (partition by StoreID) max_StoreID
  from your_table)
update t1
   set t1.Region = t2.Region
  from your_table t1
  join cte t2 on t1.StoreID = t2.StoreID 
 where t2.rn = 1 and t1.[Week] <> t2.[Week]

Open in new window

tested with your sample data.
declare @table table (StoreID int,    Region varchar(10),[Week] int)
insert @table values(1 ,               'NE' ,           1)
insert @table values(2 ,               'MW'  ,        1)
insert @table values(3 ,               'SW'   ,        1 )
insert @table values(1 ,               'NW'    ,       2)
insert @table values(2 ,               'MW'     ,      2)
insert @table values(3 ,               'SE'      ,       2)

;with cte as (
select *,
       ROW_NUMBER() over (partition by StoreID order by [Week] desc) rn,
       MAX([Week]) over (partition by StoreID) max_StoreID
  from @table)
update t1
   set t1.Region = t2.Region
  from @table t1
  join cte t2 on t1.StoreID = t2.StoreID 
 where t2.rn = 1 and t1.[Week] <> t2.[Week]

select * from @table
/*
StoreID	Region	Week
1	NW	1
2	MW	1
3	SE	1
1	NW	2
2	MW	2
3	SE	2
*/

Open in new window

0
 
LVL 41

Expert Comment

by:Sharath
ID: 34946167
But if you update the previous weeks data, you lost the history. Are you fine with that?
0
 
LVL 1

Author Comment

by:johnnyaction
ID: 34946191
Yes, I am only concerned with what the latest Region is. I save copies of the table every week anyway. I will test, thank you
0
 
LVL 1

Author Comment

by:johnnyaction
ID: 34946337
This didnt work for my data. Every week I append data for the same store ids to the table and I need every records region for that store id to be updated with the latest weeks region. I just did a check on the table after I did the update and the first value I checked was not updated? Does this make sense? Thanks for your help
0
 
LVL 1

Author Comment

by:johnnyaction
ID: 34946359
To make this even easier....The last week I entered is week number 7. If I could just simply update every region by StoreID with Week 7's Region and then I could change the week number every week then that would work...What do you think?
0
 
LVL 41

Expert Comment

by:Sharath
ID: 34946378
Can you post the not working data?
0
 
LVL 1

Author Comment

by:johnnyaction
ID: 34946456
This is data that is in my table right now..

Store id     Region              week
33             MW Racks            6
33             MW Racks            7
33             NW/NCAL Racks   5


Week 5 was NW/NCAL Racks prior to the update I ran. Week 6 was already MW Racks and so was Week 7. What I need is for every weeks Region to be MW Racks because that was what Week 7(Which is the latest week to be inserted) is.

Thank
0
 
LVL 41

Accepted Solution

by:
Sharath earned 2000 total points
ID: 34946711
I got the Region updated for your latest data also. Are you running exactly as I ran?
declare @table table (StoreID int,    Region varchar(50),[Week] int)
insert @table values(1 ,               'NE' ,           1)
insert @table values(2 ,               'MW'  ,        1)
insert @table values(3 ,               'SW'   ,        1 )
insert @table values(1 ,               'NW'    ,       2)
insert @table values(2 ,               'MW'     ,      2)
insert @table values(3 ,               'SE'      ,       2)
insert @table values(33 ,             'MW Racks'      ,       6)
insert @table values(33 ,               'MW Racks'      ,       7)
insert @table values(33 ,               'NW/NCAL Racks'      ,   5)

;with cte as (
select *,
       ROW_NUMBER() over (partition by StoreID order by [Week] desc) rn,
       MAX([Week]) over (partition by StoreID) max_StoreID
  from @table)
update t1
   set t1.Region = t2.Region
  from @table t1
  join cte t2 on t1.StoreID = t2.StoreID 
 where t2.rn = 1 and t1.[Week] <> t2.[Week]

select * from @table
/*
StoreID	Region	Week
1	NW	1
2	MW	1
3	SE	1
1	NW	2
2	MW	2
3	SE	2
33	MW Racks	6
33	MW Racks	7
33	MW Racks	5
*/

Open in new window

0
 
LVL 1

Author Comment

by:johnnyaction
ID: 34947162
Your right,!!  Thanks for your help!!
0
 
LVL 1

Author Closing Comment

by:johnnyaction
ID: 34947163
thanks
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
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…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

604 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