如何为多个查询组合订购

时间:2015-12-02 11:37:47

标签: sql sql-server-2008

我有以下查询:

 with t1 as (select PROCESS_NAME, row_number() over (order by PROCESS_NAME ) rn from #tempDIM_INVENTRUST_PROCESS_MST ),   
      t2 as (select *, row_number() over (order by PROCESS_NAME ) rn from #tempDIM_INVENTRUST_SUB_PROCESS_MST),
      t3 as (select *, row_number() over (order by USER_NAME ) rn from #tempIvenTrust_V_USER_SKILL_DETAILS ),
      t4 as (select *, row_number() over (order by USER_NAME ) rn from #tempIvenTrust_V_USER_SKILL_DETAILS_2),
      t5 as (select *, row_number() over (order by VCHAR_CLIENT ) rn from #tempCLIENT_INFO_FPY), --clientName  
      t6 as (select *, row_number() over (order by VCHAR_PRODUCTGROUP ) rn from #tempPRODUCT_GROUP_INFO_FPY_GROUP_NAME), --groupname  
      t7 as (select *, row_number() over (order by VCHAR_PROJECT ) rn from #tempPRODUCT_GROUP_INFO_FPY_PROJECT_NAME) --projectname  


      select t1.PROCESS_NAME as PROCESS_NAME_1,'' as col1,t2.PROCESS_NAME,t2.SUB_PROCESS_NAME,'' as col2,t3.USER_NAME,
      t3.PROCESS_NAME as PROCESS_NAME_2 ,''  as col3,t4.USER_NAME as Reviewer,t4.Process_Name as PROCESS_NAME_3
      ,t5.VCHAR_CLIENT,t6.VCHAR_PRODUCTGROUP ,t7.VCHAR_PROJECT
--    into #temp
   from 
      t1 full outer join t2 on t1.rn = t2.rn
      full outer join
      t3 on t2.rn = t3.rn
      full outer join
      t4 on t3.rn = t4.rn
      full outer join
      t5 on t4.rn = t5.rn
      full outer join
      t6 on t5.rn = t6.rn
      full outer join
      t7 on t6.rn = t7.rn
      order by 
      t2.PROCESS_NAME desc,
      t3.USER_NAME desc,
      t4.USER_NAME desc,
      t5.VCHAR_CLIENT desc,
      t6.VCHAR_PRODUCTGROUP desc,
      t7.VCHAR_PROJECT desc

这给了我以下结果:

 Col1       Col2  Col3  Col4         Col5

 NULL        1     2    NULL         NULL

 somevalue   2     3    NULL         NULL

 somevalue   2     3    somevalue    NULL

 somevalue   NULL  NULL    NULL    somevalue

如结果所示,NULL在结果之间进入。 我不想首先出现NULL。

我想要它:

 Col1       Col2  Col3  Col4         Col5

 somevalue   1     2    NULL         somevalue

 somevalue   2     3    NULL         NULL

 somevalue   2     3    NULL         NULL

 NULL      NULL  NULL    NULL      NULL

我尝试了不同的order by组合。

但未能这样做。

请帮帮我。

1 个答案:

答案 0 :(得分:1)

不幸的是,SQL Server在NULLS FIRST中还没有(还有?)支持NULLS LAST / ORDER BY。但这可以通过一个额外的密钥轻松完成:

order by (case when t2.PROCESS_NAME is not null then 1 else 2 end),
         t2.PROCESS_NAME desc,
         t3.USER_NAME desc,
         t4.USER_NAME desc,
         t5.VCHAR_CLIENT desc,
         t6.VCHAR_PRODUCTGROUP desc,
         t7.VCHAR_PROJECT desc