Anda di halaman 1dari 2

Eliminate duplicates

--**************************************
--
-- Name: Eliminate duplicates
-- Description:To elminate duplicates fr
-- om results from table in which version h
-- istory exists so you have the most curre
-- nt data only output to screen.
-- By: James Travis
--
-- Assumes:In SQL you can use subqueries
-- to build a result of data which you can
-- join back to the table. The subquery ac
-- ts as a base line of key values to make
-- duplicates disappear while still allowin
-- g verions of preiovus data to exist in t
-- he same table.
--
-- Assume you have a situation like this
-- .
-- Your company has a list of products t
-- hat occasionally changes but you want to
-- keep the previous price. They want to c
-- harge the current rate while still havin
-- g the previous rate in the same table. T
-- hey also want to be able to print a repo
-- rt which list all products current price
-- .
--
-- Our table looks like this:
--
-- Name: ProdPrice
--
-- Col1: ProdID
-- Col2: EffDate
-- Col3: Price
--
-- Col1 and 2 are the Clustered Primary
-- key so we can keep products together in
-- order of their effdate when price change
-- d. This is ideal in a product environmen
-- t as you want to access the products mos
-- t current price as fast as possible.
--
--
--

SELECT ProdPrice.* FROM


ProdPrice
INNER JOIN
(
SELECT ProdID, Max(EffDate) AS EffDate FROM ProdPrice GROUP BY ProdID
) AS CurrData
ON
ProdPrice.ProdID = CurrData.ProdID AND
ProdPrice.EffDate = CurrData.EffDate

-- Also to get the price for a specific


-- Product you add the following to the sub
-- query CurrData before the Group By:

WHERE ProdID = prodidwanttosee

-- This can also be handy if you want to


-- find duplicates to be deleted but want
-- to keep the most current, if you have ke
-- y fields that help with this (Or you can
-- add an increamenting column that you ca
-- n use then delete for your max to fix th
-- ose full line duplication issues). For t
-- he above example you just make the follo
-- wing change.

ProdPrice.EffDate != CurrData.EffDate

Anda mungkin juga menyukai