连接多个case语句

时间:2016-07-26 19:53:47

标签: sql sql-server-2008

我有以下SELECT语句在SQL Server 2008中运行良好。现在我需要将结果连接到单个结果/行,而不是最多返回4行。

正如您所推断的,此脚本会检查药物表,如果药物匹配,则会CASE结果。{/ p>

我在开头添加了DISTINCT,在最后添加了IS NOT NULL,以最大限度地减少每个不匹配药物的NULL结果,或者在多种匹配药物的情况下(即糖尿病) ,糖尿病)。

所有行都包含varchar个数据。

我已尽最大努力尝试CONCAT()COALESCE(),并且每次都做得很短。

在多行上返回正确结果的现有查询是:

Select DISTINCT a.conditions 
from
    (select 
         CASE 
            WHEN medication like 'caduet'
                THEN 'Hypertension and Cholesterol'
            WHEN medication like '%actoplus%'
                                OR medication like '%actos%'
                                OR medication like '%amaryl%'
                THEN 'Diabetes'
            WHEN medication like '%altocor%'
                                OR medication like '%altoprev%'
                                OR medication like '%zocor%'
                THEN 'Cholesterol'
            WHEN medication like '%-nitro%'
                                OR medication like '%accupril%'
                                OR medication like '%zosin%'
                THEN 'Hypertension'
            ELSE NULL
        END as Conditions
    from 
        prescriptions
    where 
        patientid = @contactid
        and status = 'Active') a
where 
    a.conditions is not null

谢谢!

2 个答案:

答案 0 :(得分:0)

可以使用STUFF

(Select DISTINCT a.conditions  =  STUFF(
                         ( SELECT ',' + CASE 
                            WHEN medication like 'caduet'
                            THEN 'Hypertension and Cholesterol'
                            WHEN medication like '%actoplus%'
                                OR medication like '%actos%'
                                OR medication like '%amaryl%'
                            THEN 'Diabetes'
                            WHEN medication like '%altocor%'
                                OR medication like '%altoprev%'
                                OR medication like '%zocor%'
                            THEN 'Cholesterol'
                            WHEN medication like '%-nitro%'
                                OR medication like '%accupril%'
                                OR medication like '%zosin%'
                            THEN 'Hypertension'
                            ELSE NULL
                            END as Conditions
                        from prescriptions
                        where patientid = @contactid
                        and status = 'Active'
                        ) a
                        where a.conditions is not null)) as 'Conditions'

答案 1 :(得分:0)

您可以使用for xml path将它们连接在一起。确切的语法更复杂:

with t as (<your query here>)
select stuff((select ',' + conditions
              from t
              for xml path(''), TYPE
             ).value('.', 'NVARCHAR(MAX)'
                    ), 1, 1, '');