简体   繁体   English

具有自连接的SQL查询

[英]SQL query with a self join

I have a table something like 我有一张桌子

create table test (
id [varchar](3),
var1 [varchar](2))

insert into test values (001, 'X1')
insert into test values (001, 'X2')
insert into test values (002, 'X3')
insert into test values (002, 'X4')
insert into test values (003, 'X5')
insert into test values (003, 'X6')

Please note that var1 is some string and cannot be sorted. 请注意,var1是一些字符串,无法排序。

i need to run a query that gives me results as 我需要运行一个查询,使我的结果为

id    var1       var2
 1     X1         X2
 2     X3         X4
 3     X5         X6

i try this query 我尝试这个查询

select distinct a.id, a.var1 as var1, b.var1 as var2 from test a join test b 
on a.id = b.id where a.var1 <> b.var1 order by a.id

but this gives me 但这给了我

id    var1       var2
 1     X1         X2
 1     X2         X1
 2     X3         X4
 2     X4         X3
 3     X5         X6
 3     X6         X5

can someone help me with this query to get the desired results? 有人可以帮助我进行此查询以获得所需的结果吗?

thanks 谢谢

How about using min() and max() : 如何使用min()max()

select id, min(var1), max(var1)
from t
group by id;

SQL tables represent unordered sets, so there is no ordering to your rows. SQL表表示无序集,因此您的行没有排序。 You might as well put them in an ordering specified by min() and max() . 您最好将它们按min()max()指定的顺序放置。

How about this? 这个怎么样?

select distinct a.id, a.var1 as var1, b.var1 as var2 from test a join test b 
on a.id = b.id where a.var1 < b.var1 order by a.id
SELECT test.ID, Max(test.var1) AS var1, Min(test.var1) AS var2
FROM test
GROUP BY test.ID;
UNION ALL
SELECT test.ID, Min(test.var1) AS var1, Max(test.var1) AS var2
FROM test
GROUP BY test.ID
Order By test.ID;

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

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