SQL Sub Query查找重复项

时间:2014-02-04 22:53:46

标签: sql-server subquery

我正在尝试创建查询以查找表中的重复项。然后我想知道有关重复的详细信息。我想我需要使用子查询,但我很难理解我需要做什么。

例如,此查询生成我的重复项:

SELECT [BINLOCATION], COUNT(*) as counted
FROM [MAS_RDP].[dbo].[IM_ITEMWAREHOUSE]
where QUANTITYONHAND > '0' 
group by BINLOCATION
having COUNT(*) > '1'

知道我想知道这些结果的细节。

IE:

SELECT ITEMCODE, BINLOCATION 
FROM IM_ITEMWAREHOUSE where BINLOCATION = (
  SELECT [BINLOCATION], COUNT(*) as counted
  FROM [MAS_RDP].[dbo].[IM_ITEMWAREHOUSE]
  where QUANTITYONHAND > '0'
  group by BINLOCATION
  having COUNT(*) > '1')

但是这会产生结果: 当未使用EXISTS引入子查询时,只能在选择列表中指定一个表达式。

3 个答案:

答案 0 :(得分:2)

在大多数数据库中执行此查询的更好方法是使用count(*)窗口函数:

select t.*
from (SELECT iw.*, COUNT(*) over (partition by binlocation) as cnt
      FROM [MAS_RDP].[dbo].[IM_ITEMWAREHOUSE]
      where QUANTITYONHAND > '0'
     ) t
where cnt > 1;

答案 1 :(得分:1)

只需从选择列表中删除COUNT(*),然后将BINLOCATION = (...更改为BINLOCATION IN (...

SELECT ITEMCODE, BINLOCATION 
FROM IM_ITEMWAREHOUSE where BINLOCATION IN (
  SELECT [BINLOCATION]
  FROM [MAS_RDP].[dbo].[IM_ITEMWAREHOUSE]
  where QUANTITYONHAND > '0'
  group by BINLOCATION
  having COUNT(*) > '1')

答案 2 :(得分:0)

您不能在子查询中返回两列来在WHERE子句中进行比较。作为一种解决方案,您可以将ITEMCODE和BINLOCATION(如ITEMCODE-BINLOCATION)与SQL代码连接起来。