简体   繁体   English

在SQL中选择DISTINCT对COLUMN

[英]SELECT DISTINCT pair of COLUMN in SQL

Consider 考虑

create table pairs ( number a, number b )

Where the data is 数据在哪里

1,4
4,1
2,4
2,4
3,2
3,2
2,3
5,1
Etc.

I'm Getting this 我得到了这个

1,4
4,1
2,4
3,2
2,3
5,1

What query gives me the distinct values the number column b has So I can see 什么查询给了我b列数b的不同值所以我可以看到

1,4
5,1
2,4
3,2

only 只要

I don't want the value in column a should be present in column b. 我不希望列a中的值应该出现在列b中。 Please help. 请帮忙。

what i need is to select distinct values on both sides of column. 我需要的是在列的两侧选择不同的值。 for eg. 例如。 if (1,2) is present then (2,1) must not be present 如果(1,2)存在则则(2,1)不得存在

You didn't state your DBMS, but this works on many DBMS ( least and greatest aren't part of the SQL standard unfortunately) 您没有说明您的DBMS,但这适用于许多DBMS(不幸的是, leastgreatest的不是SQL标准的一部分)

select distinct least(a,b), greatest(a,b)
from pairs
select distinct p1.a from pairs
inner join pairs p2 on p1.a=p2.b

You can massage your data and put the smaller value first: 您可以按摩您的数据并将较小的值放在第一位:

SELECT CASE WHEN a < b THEN a ELSE b END a,
       CASE WHEN a < b THEN b ELSE a END b
FROM pairs

Then you can select distinct from this: 然后你可以选择不同于:

SELECT DISTINCT a, b
FROM
(
    SELECT CASE WHEN a < b THEN a ELSE b END a,
           CASE WHEN a < b THEN b ELSE a END b
    FROM pairs
) x

Alternatively if there is no difference in meaning between a and b , you can enforce a constraint that forces a to always be smaller or equal to b , controlling the data on the way in. Then you can just do a simple SELECT DISTINCT . 或者,如果ab之间a含义没有区别,则可以强制执行约束,该约束强制a 始终小于或等于b ,控制进入的数据。然后,您可以执行简单的SELECT DISTINCT

您可以尝试此查询以获取列a中的所有不同值

SELECT distinct(a) FROM pairs WHERE not exists(select b from pairs where a=b)

Sounds like you need you're own extended version of DISTINCT. 听起来你需要你自己的扩展版DISTINCT。

You can do this (in SQL Server)... via a CURSOR. 您可以通过CURSOR执行此操作(在SQL Server中)。

Load up the cursor from your table. 从表中加载光标。 Loop through the cursor, pattern match and keep what you require by populating (INSERT) into a working (or temp) table in each cursor iteration. 循环遍历游标,模式匹配并通过在每个游标迭代中填充(INSERT)到工作(或临时)表中来保持所需。

Selecting from this final table would present your results. 从最终表中选择将显示您的结果。 Drop your working table, or the temp table will be dropped at the end of your session. 删除工作表,或者在会话结束时删除临时表。

Also you could put this logic in a stored procedure. 您也可以将此逻辑放在存储过程中。

Note, cursors are memory intensive, especially when not used properly. 注意,游标是内存密集型的,尤其是在未正确使用时。 But very handy for non-trivial or complex logic. 但对于非平凡或复杂的逻辑非常方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM