查找重复项并进行比较

时间:2012-06-19 16:40:06

标签: sql tsql

此查询返回与POG.Dbkey相关的产品数量。我需要找到所有重复项来比较哪些产品具有相同的产品,哪些产品具有相同数量的产品。

- 每个平面图中的总产品

select pog.DBKey
,Count(pos.DBParentProductKey)
as Total
from ix_spc_planogram as pog with (nolock)
, ix_spc_position as pos with (nolock)
where pog.dbkey = pos.dbparentplanogramkey
and pog.Value4= 358
group by  pog.dbkey 

2 个答案:

答案 0 :(得分:1)

如果我理解你的问题(不是很多),你可以选择这样的重复数量:

select pog.DBKey
,Count(pos.DBParentProductKey) as 'Total'
,Count(pog.DBKey) - 1 as 'Number Duplicates'
as Total
from ix_spc_planogram as pog with (nolock)
, ix_spc_position as pos with (nolock)
where pog.dbkey = pos.dbparentplanogramkey
and pog.Value4= 358
group by  pog.dbkey

或使用HAVING限制它:

select pog.DBKey
,Count(pos.DBParentProductKey) as 'Total'
as Total
from ix_spc_planogram as pog with (nolock)
, ix_spc_position as pos with (nolock)
where pog.dbkey = pos.dbparentplanogramkey
and pog.Value4= 358
group by  pog.dbkey
having count(pog.dbkey) > 1

答案 1 :(得分:0)

这将帮助您入门。

这是我在需要从表格中选择/删除重复时使用的模板:

Select  *
--DELETE
FROM    Table
WHERE   Table.TableID IN
(
    -- List 1 - all rows that have duplicates
    SELECT t1.TableID
    FROM Table t1
    WHERE Exists
    (
        SELECT UniqueField1, UniqueField2, Count(TableID)
        FROM Table
        WHERE Table.UniqueField1 = t1.UniqueField1
        AND UniqueField2 = t1.UniqueField2
        GROUP BY UniqueField1, UniqueField2
        HAVING Count(TableID) > 1
    )
)
AND TableID NOT IN
(
    -- List 2 - one row from each set of duplicate
    SELECT Max(TableID)
    FROM Table t2
    WHERE Exists
    (
        SELECT UniqueField1, UniqueField2, Count(TableID)
        FROM Table
        WHERE UniqueField1 = t2.UniqueField1
        AND UniqueField2 = t2.UniqueField2
        GROUP BY UniqueField1, UniqueField2
        HAVING Count(TableID) > 1
    )
    GROUP BY UniqueField1, UniqueField2
)