简体   繁体   中英

Excluding 'Nulls' from alias column

hoping you guys can help me out. Am a trainee analyst so need a hand. Please see below query:

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

In my alias column I have Nulls in there that don't match my case statement. How do I ask SQL to return my case statement excluding the Nulls in my alias column?

How about using a subquery or 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];

A word of advice: don't use single quotes for column aliases. Only use single quotes for date and string constants. You can use square braces or double quotes in SQL Server.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM