排除' Nulls'来自别名专栏

时间:2016-06-28 12:21:14

标签: sql null fetch

希望你们可以帮助我。我是一名实习分析师,所以需要一只手。请参阅以下查询:

SELECT [PATHWAY_ID], [PAS_ID], [Patient_Name], [Pathway_Specialty], [Clinician],
       [Referral_priority], [RTT_START_DTTM], [Days Waiting], [Activity Type],
       [Last Activity Type], [Next_Appt_DTTM], [First_Appointment_Flag],
       CASE WHEN [Days Waiting] <=97 AND [Next_Appt_DTTM] IS NOT NULL THEN 'Booked'
            WHEN [Days Waiting] >=98 AND [Next_Appt_DTTM] IS NULL THEN 'Unbooked'
       END AS 'Booked Status'
FROM [GWH_RTT].[rtt].[GWH_RTT_Nonadmitted_PTL]
WHERE [Referral_priority] = 'Routine'
ORDER BY 'Booked Status' DESC

在我的别名专栏中,我的Nulls与我的案例陈述不匹配。如何让SQL返回我的case语句,不包括别名列中的Null?

2 个答案:

答案 0 :(得分:1)

如何使用子查询或cte:

with q as (<your query here without the order by>)
select q.*
from q
where [Booked Status] is not null
order by [Booked Status];

建议:不要使用单引号作为列别名。仅对日期和字符串常量使用单引号。您可以在SQL Server中使用方括号或双引号。

答案 1 :(得分:1)

试试这个:

SELECT t.* 
FROM (SELECT [PATHWAY_ID], [PAS_ID], [Patient_Name], [Pathway_Specialty], [Clinician],
       [Referral_priority], [RTT_START_DTTM], [Days Waiting], [Activity Type],
       [Last Activity Type], [Next_Appt_DTTM], [First_Appointment_Flag],
       CASE WHEN [Days Waiting] <=97 AND [Next_Appt_DTTM] IS NOT NULL THEN 'Booked'
            WHEN [Days Waiting] >=98 AND [Next_Appt_DTTM] IS NULL THEN 'Unbooked'
       END AS 'Booked Status'
FROM [GWH_RTT].[rtt].[GWH_RTT_Nonadmitted_PTL]
WHERE [Referral_priority] = 'Routine'
) t
WHERE t.[Booked Status] IS NOT NULL
ORDER BY [Booked Status] DESC