简体   繁体   中英

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.

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() :

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

SQL tables represent unordered sets, so there is no ordering to your rows. You might as well put them in an ordering specified by min() and 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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