如何选择不同的列并返回非空值

时间:2014-07-08 14:21:23

标签: sql sql-server join distinct

我有很多表与一个主表有关系。 我希望能够连接这些表,同时从每一行中选择不同的值,并且只返回非空值吗?

例如,

 ColA    ColB    ColC
 Black   3       Car
 Red     18      60

到目前为止,这是我的查询:

SELECT DISTINCT FormTitle, FormSection FROM Table1 c
FULL OUTER JOIN Table2 l
   ON c.FormSectionID = l.FormSectionID
FULL OUTER JOIN Table3 f
   ON c.FormID = f.FormID

我希望FormTitle列具有所有distinct和non null值,并且FormSection列等相同。

当我添加WHERE FormTitle IS NOT NULL且FormSection IS NOT NULL时,以下是我的结果

FormTitle                                   FormSection
Activities                                  Activities
Annual Program Data Demographic             Demographics
Annual Program Data Screening and Outreach  Other Diseases (Not Eligible for RECA)
Annual Program Data Screening and Outreach  Outreach/Education Encounters
Annual Program Data Screening and Outreach  Program Activities by Type
Annual Program Data Screening and Outreach  RECA-Eligible Diseases by Exposure Category

2 个答案:

答案 0 :(得分:2)

处理NULL时,请使用IS NULLIS NOT NULL

 SELECT DISTINCT FormTitle, FormSection 
 FROM Table1 c
 FULL OUTER JOIN Table2 l
   ON c.FormSectionID = l.FormSectionID 
 FULL OUTER JOIN Table3 f
  ON c.FormID = f.FormID
 WHERE FormTitle IS NOT NULL 
   AND FormSection IS NOT NULL

答案 1 :(得分:0)

这是一个奇怪的请求,但可以做到。在这样的事情上的表现并不会很壮观,但在一个小数据集上它应该不是一个问题。我用你发布的例子来帮忙。如果你能以这样的消费格式发布ddl和样本,那将非常有用。

if OBJECT_ID('tempdb..#Something') is not null
    drop table #Something

create table #Something
(
    Title varchar(50),
    FormSection varchar(50)
)

insert #Something
select 'Activities', 'Activities' union all
select 'Annual Program Data Demographic', 'Demographics' union all
select 'Annual Program Data Screening and Outreach', 'Other Diseases (Not Eligible for RECA)' union all
select 'Annual Program Data Screening and Outreach', 'Outreach/Education Encounters' union all
select 'Annual Program Data Screening and Outreach', 'Program Activities by Type' union all
select 'Annual Program Data Screening and Outreach', 'RECA-Eligible Diseases by Exposure Category';

with Titles as
(
    select Title, ROW_NUMBER() over (order by (select null)) as RowNum
    from #Something
    group by Title
)
, FormSections as
(
    select FormSection, ROW_NUMBER() over (order by (select null)) as RowNum
    from #Something
    group by FormSection
)

select FormSection, Title
from
(
    select FormSection, Title
    from FormSections fs
    left join Titles t on fs.RowNum = t.RowNum

    union all

    select FormSection, Title
    from Titles t
    left join FormSections fs on fs.RowNum = t.RowNum
) x
group by FormSection, Title