我必须根据第一列连接同一个表中的两行

时间:2015-01-22 12:05:54

标签: sql-server sql-server-2008

我在这里显示表

Column_1                                                Column_2
------------------------------------------------------------------------------
GERD                            Onset: 3 Days. Pain scale: 9/10. 
hyperlipidemia                  The diabetes started in 2004 and is controlled.
asthma                          Onset: 6 hours ago.  The initial visit date was 
headache                        Onset: 1 Day.  The severity of the problem is 
hyperlipidemia (comments)       This is a test Comment where i can try
asthma (comments)               Test Comment for the query

我想要的是这个

Column_1                                                Column_2
    ------------------------------------------------------------------------------
    GERD                            Onset: 3 Days. Pain scale: 9/10.     
    hyperlipidemia                  The diabetes started in 2004 and is controlled. Comment :  This is a test Comment where i can try
    asthma                          Onset: 6 hours ago.  The initial visit date was 
    headache                        Onset: 1 Day.  The severity of the problem is. Comment : Test Comment for the query        

我的SQL声明:

 select a.create_timestamp, a.Column_1 as Name, a.Column_2+b.Column_2 as DetailsAndComment from HOPI_ex_ a, HOPI_ex_ b
where a.Column_1+' (comments)' = b.Column_1

我只得到两排 Gerd和高脂血症

1 个答案:

答案 0 :(得分:2)

您只获得两行的原因是您的where子句,它会过滤掉没有相应注释的行。我认为使用左连接应该做你想要的。请试试这个:

select 
    a.create_timestamp, 
    a.Column_1 as Name, 
    case when b.Column_2 is null then a.Column_2 else  a.Column_2 + ' Comment: ' + b.Column_2 end as DetailsAndComment 
from HOPI_ex_ a
left join HOPI_ex_ b on a.Column_1 + ' (comments)' = b.Column_1
where a.Column_1 not like '%(comments)%'

使用您的示例数据,上面查询的结果将是:

Name              DetailsAndComment
----------------- -----------------------------------------
GERD              Onset: 3 Days. Pain scale: 9/10.
hyperlipidemia    The diabetes started in 2004 and is controlled. Comment: This is a test Comment where i can try
asthma            Onset: 6 hours ago.  The initial visit date was Comment: Test Comment for the query
headache          Onset: 1 Day.  The severity of the problem is