如何编写以下sql查询

时间:2014-03-11 05:12:49

标签: sql sql-server

这是我的表结构

enter image description here

我在发布这个问题之前试过这个:

select x.col1,x.col2 from 
(
(select A from #t union all select C from #t) col1,
(select B from #t union all select D from #t) col2
)as x 

5 个答案:

答案 0 :(得分:3)

你可以这样试试。

Select A,B FROM #T
UNION ALL
Select C,D FROM #T WHERE C is not null

答案 1 :(得分:1)

我会这样做

SELECT T1.A AS A_or_C, T1.B AS B_or_D FROM table_name T1
UNION
SELECT T2.C AS A_or_C, T2.D AS B_or_D FROM table_name T2

这是绝对清楚的。

干杯

答案 2 :(得分:0)

select A, B from TABLE union select C, D from TABLE

答案 3 :(得分:0)

select A, B from table_name
union 
select C,D from table_name

答案 4 :(得分:0)

试试这个:

SELECT A as Name,B as Value FROM x
UNION ALL
SELECT C,D FROM x 
WHERE C IS NOT NULL

结果将是:

NAME    VALUE
AA      0.5
BB      0.5
CC      0.3
DD      0.2
BB      0.3
CC      0.5

请参阅SQL Fiddle

中的结果