SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Composite Key Query
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

cg1980
Starting Member

1 Posts

Posted - 03/18/2014 :  17:34:41  Show Profile  Reply with Quote
I am new to sql and have been scratching my head all day. I'm using sql server 2008.

My table (run_history) contains a composite key (runddate & id) and lists anytime a transaction occurs for that record including the modification date & time, which user made the change, and what the change was.

rundate id moddate modtime name what
2014-03-18 001-A 2014-03-18 14:15:30 mary created record
2014-03-18 002-A 2014-03-18 14:17:30 john created record
2014-03-18 010-A 2014-03-18 14:18:30 mary created record
2014-03-18 001-A 2014-03-18 14:19:45 rob added phone number
2014-03-18 011-A 2014-03-18 14:20:50 mary added address
2014-03-18 001-A 2014-03-18 14:34:32 john changed phone number
2014-03-18 002-A 2014-03-18 14:45:30 sue added phone number
2014-03-18 002-A 2014-03-18 15:25:30 mary changed phone number

I am trying to create a view which will return the rundate, id, and who made the change when the reason contains 'phone number' changed or added. I also only want to include the most recent modification time and disregard any previous changes.

Suggestions on how to proceed?

Thanks! Chris

ScottPletcher
Constraint Violating Yak Guru

USA
344 Posts

Posted - 03/18/2014 :  17:45:32  Show Profile  Reply with Quote
Not a lot of details, but here's my best guess:


SELECT derived.*
FROM (
    SELECT
        rundate, id, moddate, modtime, name, what,
        ROW_NUMBER() OVER(PARTITION BY id ORDER BY moddate DESC, modtime DESC) AS row_num
    FROM dbo.tablename
    WHERE
        what LIKE '%phone number%'
) AS derived
WHERE
    row_num = 1
ORDER BY
    id

Go to Top of Page

ScottPletcher
Constraint Violating Yak Guru

USA
344 Posts

Posted - 03/18/2014 :  17:46:16  Show Profile  Reply with Quote
For the final view, naturally add
CREATE VIEW viewname AS
and remove the ORDER BY.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.08 seconds. Powered By: Snitz Forums 2000