Not include this specific date in the query when using BETWEEN operator in SQL Server 2008 - sql

There is one specific date that I do not want to include in this which is "04/08/2020". I want to filter all the records from the beginning of the year till now but not 04/08/2020. How can I do that?
SELECT
dbo.PID_RespiratorFit.PTIDNum,
rtrim(acp.LastName) + ', ' + rtrim(acp.FirstName) AS Name,
acp.BadgeID AS ID,
dbo.Patient.PcFLD01 as Organization,
dbo.PID_RespiratorFit.Risk AS Exposure,
UPPER(dbo.PID_RespiratorFit.Type) AS Mask_Type,
dbo.PID_RespiratorFit.OHSNotes AS Comments,
dbo.PID_RespiratorFit.MedicallyClearedDate AS Medically_Cleared,
dbo.PID_RespiratorFit.TrainingCompletedDate,
dbo.PID_RespiratorFit.DateIssued AS N95_Fittest_Completed,
dbo.PID_RespiratorFit.Mask AS N95_respirator,
dbo.PID_RespiratorFit.PAPR,
dbo.PID_RespiratorFit.PaprFitTestDate AS PAPR_Fittest_Completed,
dbo.PID_RespiratorFit.Active,
DATEADD(year, 1, dbo.PID_RespiratorFit.MedicallyClearedDate) AS Compliant_Through
FROM dbo.PID_RespiratorFit LEFT JOIN
dbo.Patient ON dbo.PID_RespiratorFit.PTIDNum = dbo.Patient.PTIDNUM LEFT JOIN
dbo.aspnet_CustomProfile acp ON dbo.Patient.PGuid = acp.UserId
WHERE (dbo.PID_RespiratorFit.DateIssued BETWEEN '1-1-2020' AND Getdate())

Use standard date formats! Then:
WHERE dbo.PID_RespiratorFit.DateIssued BETWEEN '2020-01-01' AND Getdate() and
dbo.PID_RespiratorFit.DateIssued <> '2020-04-08' -- or is that 2020-08-04???
If the date is really a date/time, then use:
WHERE dbo.PID_RespiratorFit.DateIssued BETWEEN '2020-01-01' AND Getdate() and
CONVERT(DATE, dbo.PID_RespiratorFit.DateIssued) <> '2020-04-08' -- or is that 2020-08-04???
I also strongly recommend table aliases so the query is much easier to write and read. For example:
SELECT . . .
FROM dbo.PID_RespiratorFit rf LEFT JOIN
dbo.Patient p
ON rf.PTIDNum = p.PTIDNUM LEFT JOIN
dbo.aspnet_CustomProfile acp
ON p.PGuid = acp.UserId
WHERE rf.DateIssued BETWEEN '2020-01-01' AND Getdate() AND
CONVERT(DATE, rf.DateIssued) <> '2020-04-08' -- or is that 2020-08-04???

You can try the below - adding an extra condition
SELECT
dbo.PID_RespiratorFit.PTIDNum,
rtrim(acp.LastName) + ', ' + rtrim(acp.FirstName) AS Name,
acp.BadgeID AS ID,
dbo.Patient.PcFLD01 as Organization,
dbo.PID_RespiratorFit.Risk AS Exposure,
UPPER(dbo.PID_RespiratorFit.Type) AS Mask_Type,
dbo.PID_RespiratorFit.OHSNotes AS Comments,
dbo.PID_RespiratorFit.MedicallyClearedDate AS Medically_Cleared,
dbo.PID_RespiratorFit.TrainingCompletedDate,
dbo.PID_RespiratorFit.DateIssued AS N95_Fittest_Completed,
dbo.PID_RespiratorFit.Mask AS N95_respirator,
dbo.PID_RespiratorFit.PAPR,
dbo.PID_RespiratorFit.PaprFitTestDate AS PAPR_Fittest_Completed,
dbo.PID_RespiratorFit.Active,
DATEADD(year, 1, dbo.PID_RespiratorFit.MedicallyClearedDate) AS Compliant_Through
FROM dbo.PID_RespiratorFit LEFT JOIN
dbo.Patient ON dbo.PID_RespiratorFit.PTIDNum = dbo.Patient.PTIDNUM LEFT JOIN
dbo.aspnet_CustomProfile acp ON dbo.Patient.PGuid = acp.UserId
WHERE (dbo.PID_RespiratorFit.DateIssued BETWEEN '1-1-2020' AND Getdate())
AND cast(dbo.PID_RespiratorFit.DateIssued as date)<>'2020-04-08'

Related

I need to add additional columns to my application that are not part of GROUPBY statement

I need some help with my SQL command. I have a VB.net application that uses few sql tables to get the final result. I need to add few additional columns from TableC into my application, but these columns are not part of GROUPBY function.
I tried to add simple select function to the code, but I always get the same error:
$"
SET NOCOUNT ON;
SELECT CONVERT(VARCHAR(10), r.PossibleDate, 120) as [Date],
**SELECT r.GStart as GStart,**
SUM(ISNULL(r.ElecCheckIn, 0)) as CheckIn,
SUM(ISNULL(r.ElecCheckOut, 0)) as CheckOut,
SUM(ISNULL(r.JPAmount, 0)) as AttAmountJP,
SUM(ISNULL(r.MeteredAttAmountCC, 0)) as AttAmountCC,
SUM(ISNULL(r.MeteredMachAmount, 0)) as MachAmount,
SUM(ISNULL(r.MeteredAttAmount, 0)) as AttAmount,
SUM(ISNULL(r.ElecCheckIn, 0) - ISNULL(r.ElecCheckOut, 0) - ISNULL(r.JPAmount, 0) - ISNULL(r.MeteredAttAmountCC, 0) - ISNULL(r.MeteredMachAmount, 0) - ISNULL(r.MeteredAttAmount, 0)) as NetWin
FROM dbo.CDS_TableA sm (NOLOCK)
INNER JOIN dbo.bb_tableB st (NOLOCK)
ON sm.TableB_Id=st.SlotB_Id
AND sm.TableBRevision=st.TabelBRevision
INNER JOIN dbo.TableC r (NOLOCK)
ON sm.TableA_ID=r.TableA_ID
AND r.PossibleDate BETWEEN '{dtStart.Value.ToString("yyyy-MM-dd")} 00:00:00' AND '{dtEnd.Value.ToString("yyyy-MM-dd")} 23:59:59'
AND r.Period_ID=4
INNER JOIN dbo.BB_TableD rh (NOLOCK)
ON sm.TableA_ID=rh.TableA_ID
AND r.PossibleDate=rh.PossibleDate
AND sm.Revision=rh.Revision
WHERE sm.OnFloorFlag = 1
AND sm.Calc_ID NOT IN (2,5)
GROUP BY r.PossibleDate
ORDER BY r.PossibleDate;
I always get an error that GStart is not contained in either an aggregate function or the GROUP BY clause.
Simply JOIN the aggregate level to unit level which can be facilitated with a CTE. Run this entire statement below including WITH clause.
WITH agg AS (
SELECT CONVERT(VARCHAR(10), r.PossibleDate, 120) as [Date],
SUM(ISNULL(r.ElecCheckIn, 0)) as CheckIn,
SUM(ISNULL(r.ElecCheckOut, 0)) as CheckOut,
SUM(ISNULL(r.JPAmount, 0)) as AttAmountJP,
SUM(ISNULL(r.MeteredAttAmountCC, 0)) as AttAmountCC,
SUM(ISNULL(r.MeteredMachAmount, 0)) as MachAmount,
SUM(ISNULL(r.MeteredAttAmount, 0)) as AttAmount,
SUM(ISNULL(r.ElecCheckIn, 0) -
ISNULL(r.ElecCheckOut, 0) -
ISNULL(r.JPAmount, 0) -
ISNULL(r.MeteredAttAmountCC, 0) -
ISNULL(r.MeteredMachAmount, 0) -
ISNULL(r.MeteredAttAmount, 0)) as NetWin
FROM dbo.CDS_TableA sm (NOLOCK)
INNER JOIN dbo.bb_tableB st (NOLOCK)
ON sm.TableB_Id =s t.SlotB_Id
AND sm.TableBRevision=st.TabelBRevision
INNER JOIN dbo.TableC r (NOLOCK)
ON sm.TableA_ID= r.TableA_ID
AND r.PossibleDate BETWEEN '{dtStart.Value.ToString("yyyy-MM-dd")} 00:00:00'
AND '{dtEnd.Value.ToString("yyyy-MM-dd")} 23:59:59'
AND r.Period_ID=4
INNER JOIN dbo.BB_TableD rh (NOLOCK)
ON sm.TableA_ID=rh.TableA_ID
AND r.PossibleDate=rh.PossibleDate
AND sm.Revision=rh.Revision
WHERE sm.OnFloorFlag = 1
AND sm.Calc_ID NOT IN (2,5)
GROUP BY r.PossibleDate
)
SELECT r.GStart as GStart, agg.* --- ADD OTHER r FIELDS
FROM dbo.TableC r
INNER JOIN agg ON CONVERT(VARCHAR(10), r.PossibleDate, 120) = agg.[Date]
ORDER BY r.PossibleDate
Aside: While I know nothing of vb.net, I do know running SQL at application layer and your concatenation of dates above should be parameterized values which is a programming industry best practice. See How do I create a parameterized SQL query? Why Should I? Also, use NOLOCK with caution.

Teradata SQL CASE Statement with multiple conditions

I have the below SQL query -
select distinct HospitalAcctID,
AdmitDate,
DischargeDate,
PatMRN,
Pat_id,
ICD,
MedCenter,
(case when SeqCount =1 and AdmitDate > '06/01/2013' and AdmitDate < '06/01/2018' then 1 else null end ) Firstdiag
from
(
select distinct acct.HSP_ACCOUNT_ID as HospitalAcctID,
cast(acct.ADM_DATE_TIME as date format 'mm/dd/yyyy') as AdmitDate,
cast(acct.DISCH_DATE_TIME as date format 'mm/dd/yyyy') as DischargeDate,
pat.pat_mrn_id as PatMRN,
pat.pat_id as Pat_id,
REF_BILL_CODE as ICD,
grp7.NAME AS MedCenter,
row_number() over (partition by PatMRN order by AdmitDate) as SeqCount
from acct
inner join pat on pat.pat_id = acct.pat_id
inner join hspenc on hspenc.CSN_ID = acct.CSN_ID
inner join dx on acct.ACCOUNT_ID = dx.ACCOUNT_ID and line = 1
inner join edg on dx.DX_ID = edg.DX_ID
inner join loc on loc.LOC_ID = acct.LOC_ID
inner join grp7 ON loc.RPT_GRP_SEVEN = grp7.RPT_GRP_SEVEN
where
grp7.NAME = 'SMC AREA'
and ADMIT_CONF_STAT_C in ('1','4')
and (edg. REF_BILL_CODE in ('431',
'431')
)
and ADT_PAT_CLASS_C in ('1204','12113')
order by AdmitDate;
)Admit
But I am getting the below syntax error -
Syntax error, expected something like an 'EXCEPT' keyword, 'UNION' Keyword or a 'MINUS' keyword between 'AdmitDate' and ','
In the outer select statement, I am trying to get the min (first ) date when the was first diagnosed. I also want to get only the patients who were diagnosed between 6/2013 to 6/2018 which is why I have the CASE statement. But the CASE statement is giving me error.
As #BarbarosĂ–zhan already wrote, remove the last line order by AdmitDate; in the Derived Table.
But there's no need for ROW_NUMBER:
select distinct acct.HSP_ACCOUNT_ID as HospitalAcctID,
cast(acct.ADM_DATE_TIME as date format 'mm/dd/yyyy') as AdmitDate,
cast(acct.DISCH_DATE_TIME as date format 'mm/dd/yyyy') as DischargeDate,
pat.pat_mrn_id as PatMRN,
pat.pat_id as Pat_id,
REF_BILL_CODE as ICD,
grp7.NAME AS MedCenter,
case when -- current rows is first row
min(AdmitDate)
over (partition by PatMRN) = AdminDate
-- current row within date range
and AdminDate >= DATE '2013-06-01' and AdmitDate < DATE '2018-06-01'
then 1
else null
end as Firstdiag
from acct
inner join pat on pat.pat_id = acct.pat_id
inner join hspenc on hspenc.CSN_ID = acct.CSN_ID
inner join dx on acct.ACCOUNT_ID = dx.ACCOUNT_ID and line = 1
inner join edg on dx.DX_ID = edg.DX_ID
inner join loc on loc.LOC_ID = acct.LOC_ID
inner join grp7 ON loc.RPT_GRP_SEVEN = grp7.RPT_GRP_SEVEN
where
grp7.NAME = 'SMC AREA'
and ADMIT_CONF_STAT_C in ('1','4')
and (edg. REF_BILL_CODE in ('431',
'431')
)
and ADT_PAT_CLASS_C in ('1204','12113')
order by AdmitDate;
I also switched to a Standard SQL date literal DATE '2013-06-01' instead of '06/01/2013'. There's only one possible format for the former (DATE 'YYYY-MM-DD') while the latter depends on the FORMAT of the base column and might fail when it changes (of course not in your query, because you defined it in the CAST).

SQL - replace returned data with other data

I am retrieving data using the SQL syntax below:
SELECT TOP 5 EventId, EventTime, DeviceName, Comment, Tenant, TenantName, Individual,
InetDb.dbo.Individuals.FirstName, InetDb.dbo.Individuals.LastName, InetDb.dbo.IndivImages.UserImage
FROM taclogdata.dbo.Event
LEFT JOIN InetDb.dbo.Tenants
ON taclogdata.dbo.Event.Tenant = InetDb.dbo.Tenants.TenantId
LEFT JOIN InetDb.dbo.Individuals
ON taclogdata.dbo.Event.Individual = InetDb.dbo.Individuals.IndivId
AND taclogdata.dbo.Event.Tenant = InetDb.dbo.Individuals.TenantNdx
LEFT JOIN InetDb.dbo.IndivImages
ON InetDb.dbo.Individuals.IndivId = InetDb.dbo.IndivImages.IndivNdx
AND InetDb.dbo.Individuals.TenantNdx = InetDb.dbo.IndivImages.TenantNdx
WHERE (taclogdata.dbo.Event.EventTime > DATEADD(hh, -3, GETDATE())AND taclogdata.dbo.Event.EventTime < GETDATE())
AND (taclogdata.dbo.Event.Comment='Reader entry' OR taclogdata.dbo.Event.Comment='Reader exit')
AND (taclogdata.dbo.Event.DeviceName = 'L9 1/4/1'
OR taclogdata.dbo.Event.DeviceName='L1 2/1/1-2 MainD'
OR taclogdata.dbo.Event.DeviceName='L1 2/1/3-4 MainD'
OR taclogdata.dbo.Event.DeviceName='L1 2/6/1-2 Stair'
OR taclogdata.dbo.Event.DeviceName='L1 2/2/1-2 FDT1')
ORDER BY taclogdata.dbo.Event.EventTime DESC
This code works fine, however I'm trying to simplify the results.
I'm trying to simplify what the query returns, by replacing the DeviceName value from e.g. L1 2/1/3-4 MainD to Main Door when the results are shown (not replace the actual data in the database)
How may I achieve this please ?
Thanks in advance,
J
try this use replace function
SELECT TOP 5 EventId, EventTime, replace(DeviceName,'L1 2/1/3-4 MainD','L1 2/1/3-4 Main Door') as DeviceName, Comment, Tenant, TenantName, Individual,
InetDb.dbo.Individuals.FirstName, InetDb.dbo.Individuals.LastName, InetDb.dbo.IndivImages.UserImage
FROM taclogdata.dbo.Event
LEFT JOIN InetDb.dbo.Tenants
ON taclogdata.dbo.Event.Tenant = InetDb.dbo.Tenants.TenantId
LEFT JOIN InetDb.dbo.Individuals
ON taclogdata.dbo.Event.Individual = InetDb.dbo.Individuals.IndivId
AND taclogdata.dbo.Event.Tenant = InetDb.dbo.Individuals.TenantNdx
LEFT JOIN InetDb.dbo.IndivImages
ON InetDb.dbo.Individuals.IndivId = InetDb.dbo.IndivImages.IndivNdx
AND InetDb.dbo.Individuals.TenantNdx = InetDb.dbo.IndivImages.TenantNdx
WHERE (taclogdata.dbo.Event.EventTime > DATEADD(hh, -3, GETDATE())AND taclogdata.dbo.Event.EventTime < GETDATE())
AND (taclogdata.dbo.Event.Comment='Reader entry' OR taclogdata.dbo.Event.Comment='Reader exit')
AND (taclogdata.dbo.Event.DeviceName = 'L9 1/4/1'
OR taclogdata.dbo.Event.DeviceName='L1 2/1/1-2 MainD'
OR taclogdata.dbo.Event.DeviceName='L1 2/1/3-4 MainD'
OR taclogdata.dbo.Event.DeviceName='L1 2/6/1-2 Stair'
OR taclogdata.dbo.Event.DeviceName='L1 2/2/1-2 FDT1')
ORDER BY taclogdata.dbo.Event.EventTime DESC
Here my suggestions:
If you can replace the data in your SELECT for example:
SELECT REPLACE(DeviceName,N'2/1/3-4 MainD',N'Main Door')
If you have many replacements, I would suggest to create a temporary table, join it and take the replacement from the temporary table.
The specific answer to your question is to use REPLACE() or a CASE statement. However, you should also change the WHERE clause to use IN and use table aliases so the code is easier to write and to read:
FROM taclogdata.dbo.Event e LEFT JOIN
InetDb.dbo.Tenants t
ON e.Tenant = t.TenantId LEFT JOIN
InetDb.dbo.Individuals i
ON e.Individual = i.IndivId AND e.Tenant = i.TenantNdx LEFT JOIN
InetDb.dbo.IndivImages ii
ON i.IndivId = ii.IndivNdx AND Ii.TenantNdx = ii.TenantNdx
WHERE (e.EventTime > DATEADD(hour, -3, GETDATE()) AND
e.EventTime < GETDATE()
) AND
e.Comment IN ('Reader entry', 'Reader exit') AND
e.DeviceName IN ('L9 1/4/1', 'L1 2/1/1-2 MainD', 'L1 2/1/3-4 MainD',
'L1 2/6/1-2 Stair', 'L1 2/2/1-2 FDT1'
)

Select where no value is greater than X

I'm currently running this query:
SELECT DISTINCT f.FormName
FROM PatientTask as pt
INNER JOIN ClinicTask ct
ON pt.fTaskKey = ct.fTaskKey
INNER JOIN Form f
ON ct.fFormKey = f.FormKey
WHERE pt.TaskTargetDate <= CONVERT(datetime, '2012-01-01');
Now, clearly this is just going to return FormName that have a TaskTargetDate that is earlier than January 1st 2012. What I'm trying to do is find FormNames that do not have a TaskTargetDate which exists in the last 2 years. So if there's a form with a TaskTargetDate in 2010, 2011, and 2013, it should be excluded entirely from the query return because of that 2013 date.
Essentially I'm looking for old forms which are no longer being used.
A NOT IN should give you those results:
Select DISTINCT f.FormName
FROM Form f
WHERE f.FormKey NOT IN
(
SELECT ct.fFormKey
From PatientTask as pt
Inner Join ClinicTask ct on pt.fTaskKey = ct.fTaskKey
WHERE pt.TaskTargetDate >= CONVERT(datetime, '2012-01-01')
)
Also the CONVERT is not necessary - SQL will automatically parse '2012-01-01' as a date since it's being compared to a date value
You can use left outer join:
Select
DISTINCT f.FormName, pt.fTaskKey
From
Form f left outer join ClinicTask ct
on ct.fFormKey = f.FormKey
Inner Join
(
select fTaskKey
from PatientTask
WHERE pt.TaskTargetDate >= CONVERT(datetime, '2012-01-01')
) pt
on pt.fTaskKey = ct.fTaskKey
where ct.fFormKey is null

SQL select where date is a week or younger

I need to select records that are a week or less in age, by this column: dbo.mod_employmentAppProfile.dateSubmitted
Note, the #arguments.departmentID# is a coldfusion tag.
Here's my query:
SELECT
dbo.pro_Profile.profileID,
dbo.pro_Profile.firstName,
dbo.pro_Profile.lastName,
dbo.pro_Profile.isDeleted,
dbo.pro_Email.emailAddress,
dbo.mod_employmentAppJobTitles.supervisorID,
dbo.mod_employmentAppJobs.appID,
dbo.mod_employmentAppJobs.isRejected,
dbo.mod_employmentAppJobs.isDeleted AS isDeletedJobs,
dbo.mod_employmentAppJobs.emailSent,
dbo.mod_employmentAppProfile.dateAvailable,
dbo.mod_employmentAppProfile.dateSubmitted,
dbo.mod_employmentAppProfile.firstName AS appFirstName,
dbo.mod_employmentAppProfile.lastName AS appLastName,
dbo.mod_employmentAppJobTitles.title,
dbo.mod_employmentAppProfile.name,
dbo.mod_employmentAppProfile.phone,
dbo.mod_employmentAppProfile.major,
dbo.mod_employmentAppProfile.minor
FROM dbo.pro_Email
INNER JOIN dbo.pro_Profile
ON dbo.pro_Email.profileID = dbo.pro_Profile.profileID
INNER JOIN dbo.mod_employmentAppJobs
INNER JOIN dbo.mod_employmentAppJobTitles
ON dbo.mod_employmentAppJobs.jobTitleID = dbo.mod_employmentAppJobTitles.jobTitleID
INNER JOIN dbo.mod_employmentAppProfile
ON dbo.mod_employmentAppJobs.eAppID = dbo.mod_employmentAppProfile.eAppID
ON dbo.pro_Profile.profileID = dbo.mod_employmentAppJobTitles.supervisorID
WHERE (dbo.mod_employmentAppJobs.emailSent = 0)
AND (dbo.mod_employmentAppJobTitles.departmentID = #arguments.departmentID#)
AND (dbo.mod_employmentAppJobs.isRejected = 0)
I did try something like:
and (dbo.mod_employmentAppProfile.dateSubmitted < DATEADD(day, - 7, GETDATE()))
which returns no results.
Suggestions?
try
(dbo.mod_employmentAppProfile.dateSubmitted > DATEADD(day, -7, GETDATE()))