I am very very new to SQL and also self taught….so be clear please. I’m trying to add a blank column within my Data that will show if the number in the days column is:
Between 15-21 AS 15-21 days ,22-28 days AS 22-28 days ,>28 days AS breached
I can get a blank column by using ' ' AS Status
. I just need to know how to populate it
declare @HG Varchar (100) set @HG = 'Clinical Support - Health Group' SELECT distinct OURREF as [DATIX ref], DATE_OPENED as [Date opened (dd/mm/yyyy)], DATE_OF_INCIDENT as [Incident date], ORGANISATION AS [Health Group], DIRECTORATE as [Division], SPECIALTY as [Specialty], ACTUAL_LOCATION As [Exact location], SEVERITY as [Severity], DATEDIFF(Day, DATE_OPENED, CURRENT_TIMESTAMP) as Days, INCIDENT_TYPE as [Type], CATEGORY as [Category], SUBCATEGORY as [sub Category], APPROVED_CODE as [Current approval status], inc_mgr AS [Handler] FROM [CDI_PATEX_INCIDENTS] AS a JOIN dbo.DATIX_incidents_main b on a.OURREF = b.inc_ourref where OURREF not like 'SUI%' and APPROVED_CODE in ('INREV') and ORGANISATION in (@HG) and DATEDIFF(dd,DATE_OPENED,GETDATE()) between 15 and 21 UNION SELECT distinct OURREF as [DATIX ref], DATE_OPENED as [Date opened (dd/mm/yyyy)], DATE_OF_INCIDENT as [Incident date], ORGANISATION AS [Health Group], DIRECTORATE as [Division], SPECIALTY as [Specialty], ACTUAL_LOCATION As [Exact location], SEVERITY as [Severity], DATEDIFF(Day, DATE_OPENED, CURRENT_TIMESTAMP) as Days, INCIDENT_TYPE as [Type], CATEGORY as [Category], SUBCATEGORY as [sub Category], APPROVED_CODE as [Current approval status], inc_mgr AS [Handler] FROM [CDI_PATEX_INCIDENTS] AS a JOIN dbo.DATIX_incidents_main b on a.OURREF = b.inc_ourref where OURREF not like 'SUI%' and APPROVED_CODE in ('INREV') and ORGANISATION in (@HG) and DATEDIFF(dd,date_reported,GETDATE()) between 21 and 28 UNION SELECT distinct OURREF as [DATIX ref], DATE_OPENED as [Date opened (dd/mm/yyyy)], DATE_OF_INCIDENT as [Incident date], ORGANISATION AS [Health Group], DIRECTORATE as [Division], SPECIALTY as [Specialty], ACTUAL_LOCATION As [Exact location], SEVERITY as [Severity], DATEDIFF(Day, DATE_OPENED, CURRENT_TIMESTAMP) as Days, INCIDENT_TYPE as [Type], CATEGORY as [Category], SUBCATEGORY as [sub Category], APPROVED_CODE as [Current approval status], inc_mgr AS [Handler] FROM [CDI_PATEX_INCIDENTS] AS a JOIN dbo.DATIX_incidents_main b on a.OURREF = b.inc_ourref where OURREF not like 'SUI%' and APPROVED_CODE in ('INREV') and ORGANISATION in (@HG) and DATEDIFF(dd,DATE_OPENED,GETDATE()) > 28 Group by OURREF, SPECIALTY, ORGANISATION, SEVERITY, DIRECTORATE, DATE_OPENED, DATE_OF_INCIDENT, ACTUAL_LOCATION, INCIDENT_TYPE, CATEGORY, SUBCATEGORY, DATE_REPORTED, APPROVED_CODE, inc_mgr Order by Days desc
Advertisement
Answer
Why don’t you do them in one select, without unions, and use this technique?
select ...., case when DATEDIFF(dd, DATE_OPENED, GETDATE()) BETWEEN 21 AND 28 then 'x' when DATEDIFF(dd, DATE_OPENED, GETDATE()) > 28 then 'y' else 'z' end as Status from tablex