两列Null应该是第一位的

时间:2014-06-12 15:48:23

标签: sql sql-server

测试表有两列A和B.我想得到两列的空值,即。应该首先从test table.Script创建测试表:

create table test(a varchar(25),b varchar(30))

insert into test
select 'a',null
insert into test
select 'b',null
insert into test
select null,d
insert into test
select null,e
insert into test
select 'f',null
insert into test
select 'a',null
insert into test
select null,b

After insert output looks like
a   NULL
b   NULL
NULL d
NULL e
f   NULL
a   NULL
NULL b

Sql Query应首先为列a和b返回空值。

输出应该在下面。

output
-----------
a      b
-----------
NULL NULL
NULL NULL
NULL NULL
a    NULL
a    b
b    d
f    e

2 个答案:

答案 0 :(得分:1)

SELECT *
FROM @TABLE
ORDER BY CASE WHEN a IS NULL THEN '1' ELSE a END ASC,
         CASE WHEN b IS NULL THEN '1' ELSE b END ASC

WORKING SQL FIDDLE

答案 1 :(得分:0)

WITH TableA AS
(
SELECT a, ROW_NUMBER() OVER(ORDER BY a) AS RowNumber FROM test
)
, TableB AS
(
SELECT b, ROW_NUMBER() OVER(ORDER BY b) AS RowNumber FROM test
)
SELECT a,b
FROM TableA AS TA INNER JOIN TableB AS TB
ON TA.RowNumber = TB.RowNumber

应该做的工作。我已经测试了它,它可以处理您的样本数据。