使用相同的#行连接两个表,但为NULL排序

时间:2012-04-11 18:40:18

标签: sql join row-number

我需要连接两个具有相同行数的表。每个表有1列。连接没有连接列可供参考。我需要将它们并排连接,因为每个表都是单独排序的,因此数值在解析顺序中位于顶部。

Table Earners的收入值从200K降到0.我不能只选择使用2个案例,因为那时我的第一行收入超过100K,但第二行的前20个条目是NULL 。我希望第二行也按降序排序。

我在CASE中使用ORDER BY查找但是没有这样的东西。我试图阅读有关row_number()但没有一个例子似乎匹配或有意义。

drop table #20plus
select
    case
        when Income >= 20000 AND Income < 100000
        then Income end as 'mula'
into #20plus
from Earners
order by mula desc


drop table #100plus
select
    case
        when Income >= 100000
        then Income end as 'dinero'
into #100plus
from Earners
order by dinero desc

Select A.dinero, B.mula
FROM #100plus as A JOIN #20plus as B
ON A.????? = B.?????

由于A和B都按降序排序,将所有NULL移动到底部,我可以参考哪些加入两个表?

使用一个带有2个CASE语句的SELECT语句的上一个输出

dinero             mula
2.12688e+007       NULL
1.80031e+007       NULL
1.92415e+006       NULL
…                  …
NULL               93530.7
NULL               91000
NULL               84500

创建两个临时表后使用一个SELECT语句的所需输出

dinero          mula
2.12688e+007    93530.7
1.80031e+007    91000
1.92415e+006    84500
…               82500
NULL            82000
NULL            …
NULL            NULL

这是Microsoft SQL Server 2008.我对此非常陌生,所以请尽可能简明扼要地给出答案。谢谢。

2 个答案:

答案 0 :(得分:0)

Select A.dinero, B.mula
FROM #100plus as A FULL OUTER JOIN #20plus as B
ON A.dinero = B.mula
ORDER BY A.dinero,B.mula;

答案 1 :(得分:0)

如果将表分成两个并使用row_number()按降序生成数字,则可以通过row_number连接它们。注意如何生成数字 - row_number按顺序给出。

; WITH _20plus AS (
     SELECT CASE WHEN income >= 20000 AND income < 100000 
                 THEN income 
             END AS Mula,
             Row_number() OVER (ORDER BY CASE WHEN income >= 20000 AND income
                < 100000 THEN income END DESC) rn
       FROM earners
     ),
     _100plus AS (
     SELECT CASE WHEN income >= 100000 THEN income 
             END AS Dinero,
            Row_number() OVER (ORDER BY CASE WHEN income >= 100000 
                                             THEN income END DESC) rn
       FROM earners
)
SELECT a.dinero,
       b.mula
FROM _100plus AS a
   INNER JOIN _20plus AS b
      ON a.rn = b.rn