SQL Server-选择所有列之一是否唯一

时间:2018-11-10 14:20:42

标签: sql sql-server tsql sql-server-2012

我想选择多行相同的一行。例如:

col1 col2 col3 col4

  a    b    1   2
  b    b    1   2
  a    c    1   2
  b    b    1   3
  a    c    2   1

条件:仅当列(col1,col2,col3)的值与其他行不同并且col4的值是相同行的最大值时选择。

例如,预期输出为:

  a    b    1   2
  b    b    1   3
  a    c    1   2
  a    c    2   1

2 个答案:

答案 0 :(得分:4)

是的,只需将group bymax聚合一起使用

with tab(col1,col2,col3,col4) as
(
  select 'a','b',1,2 union all
  select 'b','b',1,2 union all
  select 'a','c',1,2 union all
  select 'b','b',1,3 union all
  select 'a','c',2,1        
)
  select col1, col2, col3, max(col4) as col4
    from tab
   group by col1, col2, col3;

col1  col2  col3  col4
  a     b    1     2
  a     c    1     2
  a     c    2     1
  b     b    1     3

Rextester Demo

答案 1 :(得分:1)

强制性NOT EXISTS解决方案...您的条件写为不存在的查询:

DECLARE @t TABLE (col1 varchar(100), col2 varchar(100), col3 int, col4 int);
INSERT INTO @t VALUES
('a', 'b', 1, 2),
('a', 'c', 1, 2),
('a', 'c', 2, 1),
('b', 'b', 1, 2),
('b', 'b', 1, 3);

SELECT *
FROM @t AS t
WHERE NOT EXISTS (
    SELECT 1
    FROM @t AS dup
    WHERE dup.col1 = t.col1
    AND   dup.col2 = t.col2
    AND   dup.col3 = t.col3
    AND   dup.col4 > t.col4 -- outer row has smaller col4
)

Demo on DB Fiddle