2012-06-19 93 views
-1

該查詢返回與POG.Dbkey相關的產品數量。我需要找到所有重複項以比較哪些具有相同的產品,哪些具有相同數量的產品。查找重複和比較

--Total產品在每個貨架圖

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 
+3

什麼是你的問題?你有什麼嘗試?什麼不行? – Oded

+0

你真的想要什麼? –

回答

1

如果我明白你的問題(prolly沒有),您可以選擇重複像這樣的數字:

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 
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 
)