我有一张类似
的表格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')
请注意,var1是一些字符串,无法排序。
我需要运行一个查询,将结果显示为
id var1 var2
1 X1 X2
2 X3 X4
3 X5 X6
我尝试这个查询
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
但是这给了我
id var1 var2
1 X1 X2
1 X2 X1
2 X3 X4
2 X4 X3
3 X5 X6
3 X6 X5
有人可以帮我解决这个问题吗?
感谢
答案 0 :(得分:3)
如何使用min()
和max()
:
select id, min(var1), max(var1)
from t
group by id;
SQL表代表无序集,因此您的行没有排序。您也可以将它们置于min()
和max()
指定的排序中。
答案 1 :(得分:3)
这个怎么样?
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
答案 2 :(得分:1)
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;