为重复记录获取多列

时间:2013-01-10 06:30:18

标签: sql-server-2008

我正在尝试获取多个列并显示重复的ItemCodes形成一个表。 IE浏览器。如果ItemCode重复多次。

使用查询:

SELECT ItemCode    
    ,DuplicateCount = COUNT(*)
FROM IQR1
WHERE WhsCode = 01
GROUP BY
    ItemCode   
HAVING COUNT(*) > 1  
ORDER BY COUNT(*) DESC 

我得到38条记录,每条记录的重复次数为2次。

当我尝试获取另一列ItemName时,我只返回了37条记录:

SELECT ItemCode
    ,ItemName    
    ,DuplicateCount = COUNT(*)
FROM IQR1
WHERE WhsCode = 01
GROUP BY
    ItemCode
   ,ItemName       
HAVING COUNT(*) > 1  
ORDER BY COUNT(*) DESC 

如何正确修改第一个查询以获取多列并仍然返回38条记录?

1 个答案:

答案 0 :(得分:1)

将第一个查询(通过将其放在派生表中)连接回主表,加入ItemCode。

SELECT
   I.*,
   D.DuplicateCount
FROM
   IQR1 I
   INNER JOIN (
      SELECT
         ItemCode,
         DuplicateCount = COUNT(*)
      FROM IQR1
      WHERE WhsCode = 01
      GROUP BY ItemCode   
      HAVING COUNT(*) > 1
   ) D ON I.ItemCode = D.ItemCode
ORDER BY DuplicateCount DESC