2014-09-04 50 views
0

我有一个子查询是一个大型查询的一部分,但真的我认为这个问题是孤立的子查询。如果我错了,我会很乐意发布整个事情。根据期望的数据优先级只选择一个(NOT TOP)记录库

我有一个人可能有4或5或8或0等条目的记录。我们只需要一条记录,但我们有一个偏好。我们会记录B,如果记录中的一个不存在等

本来我是加入到表

.....剪断.....

LEFT JOIN [COMMUNICATION] Comm ON Peeps.PEOPLE_ID = Comm.PEOPLE_ID 

和获得结果如

ID  FIRST  LAST  ADDY  BIZ  CELL  FAX   HOME 
21930 Person  Name  Addy 3237532500 NULL  NULL  NULL 
21930 Person  Name  Addy NULL  3237910815 NULL  NULL 
21930 Person  Name  Addy NULL  NULL  3235869055 NULL 
21930 Person  Name  Addy NULL  NULL  NULL  3238660704 
21930 Person  Name  Addy NULL  NULL  NULL  NULL 

在通讯表中我确实有5条记录,所以它不是连接问题。

现在我想在这首只有一排.... 首页 细胞 商务 传真

所以我的第一次尝试做TOP子查询(1),但当然,只有返回桌子的第一排。我读过cte并且熟悉它们,但在这种情况下,我需要能够加入并不确定如何1.请让cte按期望的业务优先级排序记录,以及2.如何加入记录。

如果你能指出我的鼻子朝着正确的方向或告诉我要学什么,我会很乐意做我自己的工作。

感谢

+0

为什么你有5行为同一人?您需要显示完整的查询。 – Donal 2014-09-04 23:37:31

回答

0

没有进一步的信息,这是我走过来:

create table #temp_table (
    [id] int, 
    [first] varchar(50), 
    [last] varchar(50), 
    [addy] varchar(50), 
    [biz] varchar(50) null, 
    [cell] varchar(50) null, 
    [fax] varchar(50) null, 
    [home] varchar(50) null 
) 

insert into #temp_table 
select 21930, 'Person', 'Name', 'Addy', '3237532500', null, null, null union all 
select 21930, 'Person', 'Name', 'Addy', null, '3237910815', null, null union all 
select 21930, 'Person', 'Name', 'Addy', null, null, '3235869055', null union all 
select 21930, 'Person', 'Name', 'Addy', null, null, null, '3238660704' union all 
select 21930, 'Person', 'Name', 'Addy', null, null, null, null 


;with ordered as(
    select 
     *, 
     rn = row_number() over(partition by id 
           order by 
            case 
             when home is not null then 1 
             when cell is not null then 2 
             when biz is not null then 3 
             when fax is not null then 4 
             else 9999 
            end 
           ) 
    from #temp_table 
) 
select 
    [id], 
    [first], 
    [last], 
    [addy], 
    [biz], 
    [cell], 
    [fax], 
    [home] 
from ordered 
where 
    rn = 1 

drop table #temp_table