0

我需要确定大量不同列中的重复项。我没有输入每个列名,而是尝试使用以下代码。这稍微更有效率,因为我只需要输入一次列名。但是,我收到此错误:

消息 164,级别 15,状态 1,第 8 行 每个GROUP BY表达式必须至少包含一个不是外部引用的列。

declare @TheCount varchar(100)
set @TheCount = 'Column_1'
select @TheCount, count(@TheCount) as LineCount
from staging
group by @TheCount
having count(@TheCount) > 1
order by 2 desc
4

2 回答 2

0

也许这个脚本会有用(假设是 Sql Server):

CREATE TABLE TEST(
a int
)

INSERT INTO TEST VALUES(1)
INSERT INTO TEST VALUES(1)
INSERT INTO TEST VALUES(2)
INSERT INTO TEST VALUES(3)
INSERT INTO TEST VALUES(4)
INSERT INTO TEST VALUES(4)

declare @TheCount varchar(100)
set @TheCount = 'a'

EXEC('select ' + @TheCount + ', count(' + @TheCount + ') as LineCount
      from test
      group by ' + @TheCount + '
      having count(' + @TheCount + ') > 1
      order by 2 desc')

你可以在这里试试这个例子。

注意:这是“Dynamic Sql Execution”的一个小例子,这里有一个链接做一点解释。

于 2013-07-12T16:24:29.393 回答
-1
DECLARE @column_list varchar(4000) = 'column_name1,column_name2,column_name3,etc';

DECLARE @sql = '
  WITH dups AS (
    SELECT 
      *,ROW_NUMBER() OVER(PARTITION BY '+@column_list'+)) AS n
    FROM table_name
  SELECT * FROM dups WHERE n > 1';

EXEC @sql;
于 2013-07-12T17:02:49.477 回答