Home Forums SQL Server 2008 T-SQL (SS2K8) Improving query performance to detect first duplicate RE: Improving query performance to detect first duplicate

  • Using what you provided, I actually came up with the following.

    create table SaleLocationXref (

    SaleID int not null,

    LocationID int not null,

    constraint SaleLocationXref_PK primary key (SaleID,LocationID)

    );

    create table Sale (

    SaleID int not null,

    SaleStart datetime not null,

    SaleEnd datetime not null,

    constraint Sale_PK primary key (SaleID)

    );

    create table SaleItemXref (

    SaleID int not null,

    ItemID int not null,

    constraint SaleItemXref_PK primary key (SaleID,ItemID)

    );

    insert into SaleLocationXref

    values (1,1),(2,1),(4,1),(5,1),(3,2);

    insert into Sale

    values (1,'01/01/2012','01/07/2012'),

    (2,'01/06/2012','01/10/2012'),

    (3,'01/01/2012','02/07/2012'),

    (4,'02/08/2012','02/15/2012'),

    (5,'01/09/2012','01/16/2012');

    insert into SaleItemXref

    values

    (1,1),(1,2),(1,3),

    (2,1),(2,4),(2,5),

    (3,5),(3,6),(3,7),

    (4,5),(4,6),(4,7),

    (5,7),(5,8),(5,1);

    GO

    with BaseData as (

    select

    six.ItemID,

    six.SaleID,

    s.SaleStart,

    s.SaleEnd,

    count(*) over (partition by six.ItemID) as ItemCnt

    from

    Sale s inner join SaleItemXref six

    on (s.SaleID = six.SaleID)

    )

    select distinct

    bd1.ItemID,

    bd1.SaleID,

    slx.LocationID,

    bd1.SaleStart,

    bd1.SaleEnd

    from

    BaseData bd1

    inner join BaseData bd2

    on (bd1.ItemID = bd2.ItemID

    and bd1.SaleID <> bd2.SaleID)

    inner join SaleLocationXref slx

    on (slx.SaleID = bd1.SaleID)

    where

    bd1.ItemCnt > 1

    and (bd1.SaleStart between bd2.SaleStart and bd2.SaleEnd or

    bd2.SaleStart between bd1.SaleStart and bd1.SaleEnd)

    order by

    bd1.ItemID,

    bd1.SaleID;

    GO

    drop table SaleLocationXref;

    drop table Sale;

    drop table SaleItemXref;

    GO