现在我有一个表 t ,表中字段 有 id(int) ,num1(varchar2) ,num2(varchar2) ,我想求的是表中有不重复的num2,和num1的总和,但现在有个难点的地方是 num1 和num2中的内容有可能相等,
t中数据 假如位 id num1 num2
1 a b
2 b d
3 c e
4 d b
5 a f
我想得到的结果应该为 (a,b,c,d,e,f) ,那这个sql语句应该怎么写呢?敬请指教!!!
t中数据 假如位 id num1 num2
1 a b
2 b d
3 c e
4 d b
5 a f
我想得到的结果应该为 (a,b,c,d,e,f) ,那这个sql语句应该怎么写呢?敬请指教!!!
union
select num2 from tb
CREATE TABLE t(id int,num1 varchar(1),num2 varchar(1))
insert into t select 1,'a','b' UNION ALL
select 2,'b','d' UNION ALL
select 3,'c','e' UNION ALL
select 4,'d','b' UNION ALL
select 5,'a','f'
DECLARE @resualt VARCHAR(200)
SET @resualt='('
SELECT @resualt=@resualt+','+num1 FROM
(
SELECT distinct num1 FROM t
UNION
SELECT distinct num2 FROM t
) Tt
SELECT REPLACE(@resualt,'(,','(')+')'
drop table t/*
(所影响的行数为 5 行)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
(a,b,c,d,e,f)(所影响的行数为 1 行)
*/
UNION
SELECT distinct num2 FROM t
union
select num2 as num1 from t;同意2楼看法,但查询的字段名字要一致。
union可以将两个以上的表中的查询结果合并在一起,并且相同的只取其一。