选择两列中具有唯一值的行 [英] SELECT rows with unique values in two columns

查看:26
本文介绍了选择两列中具有唯一值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张这样的桌子:

id          col1 col2        
----------- ---- ----------- 
1           A    5
2           A    6
3           B    5
4           B    6
5           B    7
6           C    6
7           D    7

我需要选择不超过一行且具有 col1col2 的任何确切值.例如,一种可能的解决方案是:

I need to select no more than one row with any exact value of col1 or col2. For example one possible solution is:

id          col1 col2        
----------- ---- ----------- 
1           A    5
4           B    6
7           D    7

其他可能的解决方案是:

Other possible solution is:

id          col1 col2        
----------- ---- ----------- 
3           B    5
6           C    6
7           D    7

我需要找到任何可能的解决方案.

I need to find one of any possible solutions.

算法很简单:

  1. 从表中获取任何行到输出.
  2. 从表中排除所有行col1 中的值等于 col1 中的值或col2 等于所选行中 col2 的值.
  3. 如果表不为空,请转到第 1 步.
  1. Get any row from table to an output.
  2. Exclude all rows from the table that have value in col1 equal to value of col1 or value in col2 equal to value of col2 in the selected row.
  3. If table is not empty go to step 1.

如何在 SQL SELECT 语句中实现这个逻辑?

How to implement this logic in SQL SELECT statement?

生成测试表的代码:

CREATE TABLE #t (id INT IDENTITY, col1 CHAR(1), col2 INT) ;

INSERT  INTO #t (col1, col2)
VALUES  
    ('A', 5),
    ('A', 6),
    ('B', 5),
    ('B', 6),
    ('B', 7),
    ('C', 6),
    ('D', 7);

推荐答案

SELECT  id, col1, col2
FROM    ( SELECT    * ,
                    ROW_NUMBER() OVER ( PARTITION BY col2 ORDER BY col2 ) Row#
          FROM      #t
        ) x
WHERE   x.Row# = 1

这篇关于选择两列中具有唯一值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆