I have a staging table with the following fields:
LineNumber,StudentId,EnteranceYear,Statu
s and some other fields.
There are some duplicates based on two fields (studentID and EnteranceYear)
for which I'm trying to update the older record to be active (status=1) and
all the other duplicates to be inactive by setting status=0 .I wrote this
query first
UPDATE dbo.IF_C4TRANSFORM SET
Status = 0
WHERE FileID=2565 AND
LINE_LineNumber not in
(
select max(t.LineNumber)
from MyTable t
group by t.StudentId_ID , t.EnteranceYear
having count(*) > 1
)
but it dosen't work properly.if subquery return nothing in set the status of
all records to 0 ,no matter they are duplicated or not .then I created the
following query which I don;t like at all.
I'm just wondering if there is a better way to do so:
update MyTable t set
Status = 0
WHERE FILEID=2565 and
LINE_NUMBER IN
(
SELECT t.LineNumber FROM MyTable t
WHERE FileID=2565 and
Exists
(
SELECT 1
FROM MyTable t2
WHERE t.StudentId_ID = t2.StudentId_ID AND
t.EnteranceYear = t2.EnteranceYear AND
t.LineNumber< t2.LineNumber
)
)
Thanks a lotUPDATE MyTable
SET Status = 0
WHERE FileID=2565
AND NOT EXISTS
(select * from MyTable as t
where t.StudentID = MyTable.StudentID
and t.EntranceYear = MyTable.EntranceYear
and t.LineNumber > MyTable.LineNumber)
Roy
Friday, March 9, 2012
Query optimization
Labels:
based,
database,
duplicates,
enteranceyear,
fields,
following,
linenumber,
microsoft,
mysql,
optimization,
oracle,
query,
server,
sql,
staging,
status,
studentid,
table
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment