Monday, 7 February 2011

Love to windowing functions

Technically, this post is not about romama.
This is just about how emotionally I feel about windowing functions in Sql Server 2005/2008.

Let's say we have a table



CREATE TABLE Products
(
        ProductID int NOT NULL,
        ProductName varchar(25),
        Price money NULL,
        CONSTRAINT PK_Products PRIMARY KEY NONCLUSTERED (ProductID)
 )
INSERT INTO Products VALUES (1, 'Widgets', 25)
INSERT INTO Products VALUES (2, 'Gadgets', 50)
INSERT INTO Products VALUES (3, 'Thingies', 75)
INSERT INTO Products VALUES (4, 'Whoozits', 90)
INSERT INTO Products VALUES (5, 'Whatzits', 5)
INSERT INTO Products VALUES (6, 'Gizmos', 15)
INSERT INTO Products VALUES (7, 'Widgets', 24)
INSERT INTO Products VALUES (8, 'Gizmos', 36)
INSERT INTO Products VALUES (9, 'Gizmos', 36)
GO



Removing duplicates has never been easier:



WITH a AS (
SELECT ROW_NUMBER() OVER (PARTITION BY ProductName ORDER BY ProductId) DupOrder
FROM Products )
DELETE FROM a WHERE DupOrder > 1



Fap-fap-fap

No comments:

Post a Comment