在不同列

时间:2017-11-09 11:37:41

标签: sql sql-server-2016

我有一张这样的桌子:

CREATE TABLE #my_table (
  intID int IDENTITY (1, 1),
  num_1 varchar(100) NOT NULL,
  num_2 varchar(100) NOT NULL,
  num_3 varchar(100) NOT NULL,
  num_4 varchar(100),
  num_5 varchar(100),
  isDuplicate char(1) DEFAULT 'N'
)

INSERT INTO #my_table (num_1, num_2, num_3, num_4, num_5)
  VALUES ('a', 'b', 'c', 'd', 'e')
INSERT INTO #my_table (num_1, num_2, num_3, num_4, num_5)
  VALUES ('a', 'b', 'c', 'd', 'e')
INSERT INTO #my_table (num_1, num_2, num_3, num_4, num_5)
  VALUES ('a', 'b', 'c', 'd', 'e')
INSERT INTO #my_table (num_1, num_2, num_3, num_4, num_5)
  VALUES ('a', 'b', 'a', 'd', 'e')
INSERT INTO #my_table (num_1, num_2, num_3, num_4, num_5)
  VALUES ('a', 'b', 'a', 'd', 'e')
INSERT INTO #my_table (num_1, num_2, num_3, num_4, num_5)
  VALUES ('a', 'b', 'c', 'd', 'c')

我需要在列中找到重复项并获取重复的行号。

我的结果应该是 重复行最后3行,重复标记应更新为' Y'

4 个答案:

答案 0 :(得分:1)

这也可以解决问题:

<td>{{$user->is_active == 0 ? 'Inactive':'Active' }}</td>

有关表值构造函数的更多信息,您可以找到here

答案 1 :(得分:0)

这应该可以解决问题:

select  num_1, num_2, num_3, count(*)
from #my_table
group by num_1, num_2, num_3
having count(*) > 1

此致

答案 2 :(得分:0)

这会将表中的重复列设置为'Y',如果它是重复的,你可以从那个查询

UPDATE #my_table
SET isDuplicate = 'Y'
WHERE intID IN
(
    SELECT intID
    FROM
    (
        SELECT intID, num_1, num_2, num_3,num_4, num_5,
               RANK() OVER(PARTITION BY num_1, num_2, num_3, num_4, num_5 ORDER BY intID ASC) AS [rank]
        FROM #my_table
    ) a
    WHERE [rank] > 1
);

答案 3 :(得分:0)

试试这个:

UPDATE #my_table
SET isDuplicate = 
CASE
    WHEN
    (select count(*) 
    from #my_table t2
    where t2.intID <> #my_table.intID
    and t2.num_1 = #my_table.num_1
    and t2.num_2 = #my_table.num_2
    and t2.num_3 = #my_table.num_3
    and t2.num_4 = #my_table.num_4
    and t2.num_5 = #my_table.num_5
 ) > 0 then 'Y'
 ELSE 'N'
 END