Can this Full Outer Join query be simplified? - sql

I have bill data from two sources. I want to join them to be able to see where there is a record in one set that is not in the other and vice versa. This query does what I want but I feel like it could be written more elegantly? I only want one field for the account number and bill date (M and Y), and then separate fields for the the charges in each source.
DECLARE #BillDate datetime ='2/1/2016'
SELECT ACCT_NO = COALESCE(BPFACCT,CSTACCT) ,
BillDate = COALESCE(BPFBillDate,CSTBillDate) ,
BPFCharge ,
CSTCharge ,
Delta = ROUND(COALESCE(BPFBill.BPFCharge,0)-COALESCE(CSTBill.CSTCharge,0),2)
FROM
(
SELECT
BPFACCT = acct_no ,
BPFBillDate = cast(billdate as date) ,
BPFCharge = SUM(charge)
FROM
cisbill b
JOIN
cisbilldetail bd ON b.billid=bd.billid
WHERE
billdate>=#BillDate
AND
billdate<DATEADD(MONTH, 1, #BillDate)
GROUP BY
acct_no, billdate
) BPFBill
FULL OUTER JOIN
(
SELECT CSTACCT = acct_no ,
CSTBillDate = cast(bill_date as date) ,
CSTCharge = SUM(new_charges)
FROM
cst_bill
WHERE
bill_date>=#BillDate
AND
bill_date<DATEADD(MONTH, 1, #BillDate)
GROUP BY
acct_no, bill_date
) CSTBill
ON BPFBill.BPFACCT=CSTBill.CSTACCT
AND
BPFBill.BPFBillDate=CSTBill.CSTBillDate
Appreciate any feedback!

I feel like this would give you a more accurate result..
DECLARE #StartDate DATETIME = '2/1/2016',
#EndDate DATETIME
SET #EndDate = DATEADD(MONTH, 1, #BillDate)
SELECT ACCT_NO,
MM,
YY,
BPFCharge = SUM(BPFCharge),
CSTCharge = SUM(CSTCharge)
FROM
(
SELECT acct_no,
MM = MONTH(billdate),
YY = YEAR(billdate),
BPFCharge = charge
CSTCharge = 0.00
FROM cisbill b
JOIN cisbilldetail bd ON b.billid = bd.billid
WHERE billdate >= #StartDate
AND billdate < #EndDate
UNION ALL
SELECT acct_no,
MONTH(bill_date),
YEAR(Bill_date),
0.00,
new_charges
FROM cst_bill
WHERE bill_date >= #StartDate
AND bill_date < #EndDate
) t
GROUP BY ACCT_NO,
MM,
YY

Related

SQL with while loop to DAX conversion

Trying to convert the SQL with while loop code into DAX. Trying to build this query without using temp tables as access is an issue on the database and only have views to work with. I believe best option for me is to code it in DAX. Could someone help with it.
DECLARE #sd DATETIME
DECLARE #ed DATETIME
SELECT #sd = CONVERT(DATETIME, '2021-01-31')
SELECT #ed = GETDATE()
DECLARE #date DATETIME = EOMONTH(#sd)
WHILE ( (#date) <= #ed )
BEGIN
SELECT MONTH(#date) as Month, YEAR(#date) as Year, DAY(#date) as Day, A.*
FROM [people] A
WHERE A.effective_date = (SELECT MAX(B.effective_date)
FROM [people] B
WHERE B.employee_id = A.employee_id
AND B.record_id = A.record_id
AND B.effective_date <= #date)
AND A.effective_sequence = (SELECT MAX(C.effective_sequence)
FROM [people] C
WHERE C.employee_id = A.employee_id
AND C.record_id = A.record_id
AND C.effective_date = A.effective_date)
ORDER BY A.employee_id;
SET #date = EOMONTH(DATEADD(MONTH,1,#date))
END
While you could do this as a view, you would either have to hard-code the start and end dates, or filter them afterwards (which is likely to be inefficient). Instead you can do this as an inline Table Valued Function.
We can use a virtual tally-table (generated with a couple cross-joins) to generate a row for each month
We can use row-numbering instead of the two subqueries
CREATE FUNCTION dbo.GetData (#sd DATETIME, #ed DATETIME)
RETURNS TABLE AS RETURN
WITH L0 AS (
SELECT *
FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) v(n)
),
L1 AS (
SELECT 1 n FROM L0 a CROSS JOIN L0 b
)
SELECT
MONTH(m.Month) as Month,
YEAR(m.Month) as Year,
DAY(m.Month) as Day,
p.* -- specify columns
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY m.Month, p.employee_id, p.record_id ORDER BY p.effective_date, p.effective_sequence) AS rn
FROM [people] p
CROSS JOIN (
SELECT TOP (DATEDIFF(month, #sd, #ed) + 1)
DATEADD(month, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1, EOMONTH(#sd)) AS Month
FROM L1
) m
WHERE p.effective_date <= m.Month
) p
WHERE p.rn = 1
;
Then in PowerBI you can just do for example
SELECT *
FROM dbo.GetData ('2021-01-31', GETDATE()) d
ORDER BY
d.employee_id
Note that you cannot put the ORDER BY within the function, it doesn't work.

How Can I write in my code to exclude accounts that have had a payment posted w/in last 45 days?

I'm working in SQL Server Mgmt Studio and I'm trying to identify accounts that have not had a payment posted since the last 45 days. I've tried declaring a min and max date with getdate being less than 45 days, but that didnt work. I've also tried stating "where last payment !> getdate() -45".... but this did not give me the results I was looking for. what I need the query to do is only identify accounts that truly have not had a payment post in the last 45 days. but I'm not sure how to state this in my where clause. Here's my query
DECLARE #minDate datetime;
DECLARE #maxDate datetime;
SET #minDate = GETDATE();
SET #maxDate = GETDATE() - 45;
SELECT DISTINCT
a.id,
a.FacilityCode AS [Facility],
a.accountUnit,
a.accountNum AS [Account Number],
a.amountBalance AS [Balance],
a.accountstatus AS [Status],
CONVERT(date, a.accountStatusDate) AS StatusDate,
pmtEntryDate AS [Pmt Entry Date],
v.LastLinkARpmtDate AS [Last Pmt Date],
CONVERT(date, a.accountnextactdate) AS NextActionDate,
CONVERT(date, a.rpcDate) AS RightpartyContactDate,
a.flag AS accountFlag,
pay.flag AS pmtFlag,
a.accounttype
FROM dbo.tbAccount a
JOIN dbo.tbpmtinfo pay ON a.id = pay.id
JOIN dbo.vLastPmtDate v ON v.id = a.id
FULL JOIN (SELECT id,
MAX(deDate) AS MFSLoadDate
FROM dbo.tbDataEvents (NOLOCK)
WHERE deNewVal = 'MFS'
GROUP BY id) m ON m.id = a.id
WHERE pay.flag IN ('D')
AND a.amountBalance > 0
AND a.FacilityCode IN ('PHKY', 'QANM', 'QAOH', 'QBCA', 'QBIL', 'QBTX', 'QCIL', 'QDAL', 'QEWY', 'QFAR', 'QFGA',
'QGIL', 'QHAR', 'QHIL', 'QHTN', 'QLAL', 'QLPA', 'QMIL', 'QMNC', 'QMNM', 'QMNV', 'QMOR',
'QMTN', 'QMTX', 'QMUT', 'QRIL', 'QRKY', 'QSPA', 'QTGA', 'QTKY', 'QUIL', 'QVIL', 'QWIL', 'LHFL')
AND a.amountBalance >= '1000'
AND a.accountStatus IN ('PA', 'PP', 'BPA')
AND a.flag = 'A'
AND a.accountType IN ('Resid', 'Slfpy')
--and LastLinkARpmtDate !> Getdate() -45 and accountNum = '40728597'
AND LastLinkARpmtDate BETWEEN #minDate AND #maxDate;
I would use a WHERE NOT EXISTS clause to eliminate recent activity:
SELECT DISTINCT a.id
,a.FacilityCode [Facility]
,a.accountUnit
,a.accountNum [Account Number]
,a.amountBalance [Balance]
,a.accountstatus [Status]
,convert(DATE, a.accountStatusDate) StatusDate
,pmtEntryDate [Pmt Entry Date]
,v.LastLinkARpmtDate [Last Pmt Date]
,convert(DATE, a.accountnextactdate) NextActionDate
,convert(DATE, a.rpcDate) RightpartyContactDate
,a.flag AS accountFlag
,pay.flag AS pmtFlag
,a.accounttype
FROM dbo.tbAccount AS a
JOIN dbo.tbpmtinfo AS pay ON a.id = pay.id
JOIN dbo.vLastPmtDate AS v ON v.id = a.id
FULL JOIN (
SELECT id
,Max(deDate) AS MFSLoadDate
FROM dbo.tbDataEvents(NOLOCK)
WHERE deNewVal = 'MFS'
GROUP BY id
) m ON m.id = a.id
WHERE pay.flag IN ('D')
AND a.amountBalance > 0
AND a.FacilityCode IN (
'PHKY'
,'QANM'
,'QAOH'
,'QBCA'
,'QBIL'
,'QBTX'
,'QCIL'
,'QDAL'
,'QEWY'
,'QFAR'
,'QFGA'
,'QGIL'
,'QHAR'
,'QHIL'
,'QHTN'
,'QLAL'
,'QLPA'
,'QMIL'
,'QMNC'
,'QMNM'
,'QMNV'
,'QMOR'
,'QMTN'
,'QMTX'
,'QMUT'
,'QRIL'
,'QRKY'
,'QSPA'
,'QTGA'
,'QTKY'
,'QUIL'
,'QVIL'
,'QWIL'
,'LHFL'
)
AND a.amountBalance >= '1000'
AND a.accountStatus IN (
'PA'
,'PP'
,'BPA'
)
AND a.flag = 'A'
AND a.accountType IN (
'Resid'
,'Slfpy'
)
AND NOT EXISTS (
SELECT NULL
FROM vLastPmtDate
WHERE v.id = a.id
AND CAST(v.LastLinkARpmtDate AS DATE) > CAST(dateadd(day, - 45, getdate() AS DATE))
)
AND accountNum = '40728597'
AND LastLinkARpmtDate BETWEEN #minDate
AND #maxDate;
The function dateadd() is what you need:
DATEADD (datepart , number , date)
Set #maxDate = DATEADD(DAY, -45, GETDATE());

The query I ran returns 2 of the same column which isn't allowed in tableau and I can't fix the query

I need to be able to get rid of one of the workdate and one of the sr_name columns but I can't figure out how to.
I'm getting the query returned like this:
Query
I'm also getting this error message when entered into tableau:
The column 'sr_name' was specified multiple times for 'Custom SQL Query'.
Below is the code I have. If I remove a sr_name from either subquery there will be an error in the join clause.
select *
from
(
select s.sr_name, cast(punchdatetime as date) as workdate,
((datediff(second, min(case when p.InOut = 1 then punchdatetime end),
max(case when p.InOut = 0 then punchdatetime end))/3600) - .5) as
hoursworked
from PunchClock p join ServiceReps s on p.ServRepID = s.ServRepID
where punchyear >= 2019
group by s.sr_name, cast(punchdatetime as date)
) v
join
(
select sr_name, t.*,
calls = (select count(*) from CRM_Correspondence cr where
cast(cr.DateCreated as date) = workdate and StatusType like '%call%' and
cr.ServRepID = t.servrepid),
reaches = (select count(*) from CRM_Correspondence cr where
cast(cr.DateCreated as date) = workdate and (StatusType = 'call reached'
or StatusType like '%SCHEDULE%') and cr.ServRepID = t.servrepid),
books = (select count(*) from os_appointments o where cast(o.DateCreated
as date) = workdate and isnull(o.confirmedby, o.booked_by) =
t.servrepid),
attends = (select count(*) from os_appointments o where
cast(o.DateCreated as date) = workdate and isnull(o.confirmedby,
o.booked_by) = t.servrepid and o.appointmentStatus = 'attended')
from
(
select cast(cor.datecreated as date) workdate, cor.ServRepID
from CRM_Correspondence cor
where cor.datecreated > '2019-01-01'
group by cast(cor.datecreated as date), cor.servrepid
) t
join ServiceReps sr on t.ServRepID = sr.ServRepID
) u on v.sr_name = u.sr_name and v.workdate = u.workdate
I need the same results just without the duplicate column so I can enter the query into tableau.
This is challenging because you have so many subqueries here. This could be refactored to use a single query which is what I would do. But using the existing query you could do something along these lines.
I had to format this very differently so I could isolate each piece.
select v.sr_name
, v.workdate
, v.hoursworked
, u.ServRepID
, u.calls
, u.reaches
, u.books
, u.attends
from
(
select s.sr_name
, cast(punchdatetime as date) as workdate
, ((datediff(second, min(case when p.InOut = 1 then punchdatetime end), max(case when p.InOut = 0 then punchdatetime end))/3600) - .5) as hoursworked
from PunchClock p
join ServiceReps s on p.ServRepID = s.ServRepID
where punchyear >= 2019
group by s.sr_name
, cast(punchdatetime as date)
) v
join
(
select sr_name
, t.*
, calls =
(
select count(*)
from CRM_Correspondence cr
where cast(cr.DateCreated as date) = workdate
and StatusType like '%call%'
and cr.ServRepID = t.servrepid
)
, reaches =
(
select count(*)
from CRM_Correspondence cr
where cast(cr.DateCreated as date) = workdate
and (StatusType = 'call reached' or StatusType like '%SCHEDULE%')
and cr.ServRepID = t.servrepid
)
, books =
(
select count(*)
from os_appointments o
where cast(o.DateCreated as date) = workdate and isnull(o.confirmedby, o.booked_by) = t.servrepid
)
, attends =
(
select count(*)
from os_appointments o
where cast(o.DateCreated as date) = workdate
and isnull(o.confirmedby, o.booked_by) = t.servrepid
and o.appointmentStatus = 'attended'
)
from
(
select cast(cor.datecreated as date) workdate
, cor.ServRepID
from CRM_Correspondence cor
where cor.datecreated > '2019-01-01'
group by cast(cor.datecreated as date)
, cor.servrepid
) t
join ServiceReps sr on t.ServRepID = sr.ServRepID
) u on v.sr_name = u.sr_name
and v.workdate = u.workdate

SQL Help - Finding order before current records timestamp

Forgive me if this question is confusing:
I have a patient level data with records created by Nurses and doctors.
For each patient the doctor inputs a Target daily value for each patient. The doctor may modify this target multiple time
During the course of the day the nurse enters a value with the goal of total value being equal to the target set by the doctor.
I'm trying to write a query that
1. For each patient return every value entered by the nurse and look for the most recent doctor order made prior to the nurse's recording his/her value.
The following is the SQL I've been working on
--*********************************************-***************************************************
-- As of 10/11/2018 - Runtime = 1:40 min
DECLARE #StartDate DATETIME, #EndDate DATETIME
-- Change the following 2 variables to select a different date range for patient attribution
SET #StartDate = '2018-03-01 00:00:00.000'
SET #EndDate = '2018-10-31 00:00:00.000'
--*************************************************
Select Distinct
results.LOCATION_ABBR
,results.PROTOCOL_NAME
,results.PROV_NAME
,results.MRN
,results.OSU_CSN
,results.PAT_NAME
,results.AGE_YEARS,
results.gender,
results.Race,
results.HOSP_ADMSN_TIME,
results.HOSP_DISCH_TIME,
results.OrderDate,
results.TF_ORDERED
-- ,results.TF_Datetime
,results.TF_Date
,results.TF_Time
,results.TF_Daily
,SUM(results.TF_Daily) OVER (partition by results.OSU_CSN, results.TF_Date) AS Daily_TF_Total_v2
,results.Total_Required
,results.Daily_TF_Total
-- ,results.First_TF
-- ,results.Last_TF
From (
Select Distinct
OSU_Data.LOCATION_ABBR
,OSU_Data.PROTOCOL_NAME
,OSU_Data.PROV_NAME
,OSU_Data.MRN
,OSU_Data.OSU_CSN
,OSU_Data.PAT_NAME
,OSU_Data.AGE_YEARS,
OSU_Data.gender,
Race.PatRace as Race,
OSU_Data.HOSP_ADMSN_TIME,
OSU_Data.HOSP_DISCH_TIME,
OSU_Data.DATE_USED,
OSU_Data.OrderDate,
OSU_Data.TF_ORDERED
,TF_Daily.TF_Datetime
,TF_Daily.TF_Date
,TF_Daily.TF_Time
,TF_Daily.TF_Daily
,Max(cast(OSU_Data.TF_ORDERED as numeric(9,2))) OVER (partition by OSU_Data.OSU_CSN, OSU_Data.DATE_USED) AS Total_Required
,SUM(TF_Daily.TF_Daily) OVER (partition by OSU_Data.OSU_CSN, TF_Daily.TF_Date) AS Daily_TF_Total
,row_number() over (partition by OSU_Data.OSU_CSN order by TF_Daily.TF_Datetime) First_TF
,row_number() over (partition by OSU_Data.OSU_CSN order by TF_Daily.TF_Datetime desc) Last_TF
-- ,LAG(OSU_Data.OrderDate) OVER (ORDER BY OSU_Data.OSU_CSN,OSU_Data.OrderDate,TF_Datetime) PreviousTFOrderDT
-- ,LEAD(OSU_Data.OrderDate) OVER (ORDER BY OSU_Data.OSU_CSN,OSU_Data.OrderDate,TF_Datetime) NextTFOrderDT
From
(
Select
preOSU_Data.Orderid
,preOSU_Data.PROTOCOL_ID
,preOSU_Data.PROTOCOL_NAME
,preOSU_Data.LOCATION_ABBR
,preOSU_Data.PROV_NAME
,preOSU_Data.PAT_ID
,preOSU_Data.MRN
,preOSU_Data.OSU_CSN
,preOSU_Data.PAT_NAME
,preOSU_Data.AGE_YEARS
,preOSU_Data.gender
,Race.PatRace
,preOSU_Data.OrderDate
-- ,preOSU_Data.TF_GoalHr
,preOSU_Data.HOSP_ADMSN_TIME
,preOSU_Data.HOSP_DISCH_TIME
,preOSU_Data."YEAR USED"
,preOSU_Data."MONTH USED"
,preOSU_Data.DATE_USED
,preOSU_Data."For Sorting"
,preOSU_Data.TF_ORDERED
From
(Select Distinct
ORDERS.ORDER_ID as Orderid
,CL_PRL_SS.PROTOCOL_ID
,CL_PRL_SS.PROTOCOL_NAME
,CLARITY_LOC.LOCATION_ABBR
,CLARITY_SER.PROV_NAME
,PAT_ENC_HSP.PAT_ID
,V_PAT_FACT.PAT_MRN_ID as MRN
,PAT_ENC_HSP.PAT_ENC_CSN_ID as OSU_CSN
,V_PAT_FACT.PAT_NAME
,V_PAT_FACT.AGE_YEARS
,V_PAT_FACT.SEX_NAME as gender
,ORDER_INST as OrderDate
,DATEPART(HOUR, ORDER_INST) as TF_GoalHr
,PAT_ENC_HSP.HOSP_ADMSN_TIME
,PAT_ENC_HSP.HOSP_DISCH_TIME
,YEAR(ORDER_INST) "YEAR USED"
,DATENAME(MONTH, ORDER_INST) "MONTH USED"
,DATEFROMPARTS(YEAR(ORDER_INST),MONTH(ORDER_INST),DAY(ORDER_INST)) DATE_USED
,DATEFROMPARTS(YEAR(ORDER_INST),MONTH(ORDER_INST),1) "For Sorting"
,ORD_SPEC_QUEST.ORD_QUEST_RESP as TF_ORDERED
,Max(ORDER_INST) OVER (partition by PAT_ENC_HSP.PAT_ENC_CSN_ID, DATEFROMPARTS(YEAR(ORDER_INST),MONTH(ORDER_INST),DAY(ORDER_INST))) AS Last_DailyTFGoalTimestamp
From
PAT_ENC_HSP
,ORDERS
,ORDER_PROC
,ORDER_SMARTSET
,CL_PRL_SS
,ZC_PAT_SERVICE
,ORD_SPEC_QUEST
,CL_QQUEST
,V_PAT_FACT
,CLARITY_SER
,CLARITY_ADT
,CLARITY_DEP
,CLARITY_LOC
,ZC_PATIENT_RACE
Where
(PAT_ENC_HSP.PAT_ENC_CSN_ID = ORDER_SMARTSET.PAT_ENC_CSN_ID
AND ORDERS.ORDER_ID = ORDER_SMARTSET.ORDER_ID
AND ORDER_PROC.ORDER_PROC_ID=ORDER_SMARTSET.ORDER_ID
AND ORDER_SMARTSET.SS_PRL_ID=CL_PRL_SS.PROTOCOL_ID
AND ORDERS.ORDER_ID = ORD_SPEC_QUEST.ORDER_ID
AND ORD_SPEC_QUEST.ORD_QUEST_ID = CL_QQUEST.QUEST_ID)
and PAT_ENC_HSP.PAT_ENC_CSN_ID = CLARITY_ADT.PAT_ENC_CSN_ID
and CLARITY_ADT.DEPARTMENT_ID = CLARITY_DEP.DEPARTMENT_ID
and CLARITY_DEP.REV_LOC_ID = CLARITY_LOC.LOC_ID
and PAT_ENC_HSP.PAT_ID = V_PAT_FACT.PAT_ID
and ORDER_PROC.AUTHRZING_PROV_ID = CLARITY_SER.PROV_ID
and PAT_ENC_HSP. HOSP_ADMSN_TIME between #StartDate and #EndDate
AND CL_PRL_SS.PROTOCOL_ID = 799
AND CAST(CL_QQUEST.QUEST_ID as varchar(25)) = '101960'
UNION
Select Distinct
ORDERS.ORDER_ID as Orderid
,CL_PRL_SS.PROTOCOL_ID
,CL_PRL_SS.PROTOCOL_NAME
,CLARITY_LOC.LOCATION_ABBR
,CLARITY_SER.PROV_NAME
,PAT_ENC_HSP.PAT_ID
,V_PAT_FACT.PAT_MRN_ID as MRN
,PAT_ENC_HSP.PAT_ENC_CSN_ID as OSU_CSN
,V_PAT_FACT.PAT_NAME
,V_PAT_FACT.AGE_YEARS
,V_PAT_FACT.SEX_NAME as gender
,ORDER_INST as OrderDate
,DATEPART(HOUR, ORDER_INST) as TF_GoalHr
,PAT_ENC_HSP.HOSP_ADMSN_TIME
,PAT_ENC_HSP.HOSP_DISCH_TIME
,YEAR(ORDER_INST) "YEAR USED"
,DATENAME(MONTH, ORDER_INST) "MONTH USED"
,DATEFROMPARTS(YEAR(ORDER_INST),MONTH(ORDER_INST),DAY(ORDER_INST)) DATE_USED
,DATEFROMPARTS(YEAR(ORDER_INST),MONTH(ORDER_INST),1) "For Sorting"
,ORD_SPEC_QUEST.ORD_QUEST_RESP as TF_ORDERED
,Max(ORDER_INST) OVER (partition by PAT_ENC_HSP.PAT_ENC_CSN_ID, DATEFROMPARTS(YEAR(ORDER_INST),MONTH(ORDER_INST),DAY(ORDER_INST))) AS Last_DailyTFGoalTimestamp
From
PAT_ENC_HSP
,ORDERS
,ORDER_PROC
,ORDER_METRICS
,CL_PRL_SS
,ZC_PAT_SERVICE
,ORD_SPEC_QUEST
,CL_QQUEST
,V_PAT_FACT
,CLARITY_SER
,CLARITY_ADT
,CLARITY_DEP
,CLARITY_LOC
Where
(PAT_ENC_HSP.PAT_ENC_CSN_ID = ORDER_METRICS.PAT_ENC_CSN_ID
and ORDERS.ORDER_ID = ORDER_METRICS.ORDER_ID
AND ORDER_PROC.ORDER_PROC_ID=ORDER_METRICS.ORDER_ID
AND ORDER_METRICS.PRL_ORDERSET_ID=CL_PRL_SS.PROTOCOL_ID
AND ORDERS.ORDER_ID = ORD_SPEC_QUEST.ORDER_ID
AND ORD_SPEC_QUEST.ORD_QUEST_ID = CL_QQUEST.QUEST_ID)
and PAT_ENC_HSP.PAT_ENC_CSN_ID = CLARITY_ADT.PAT_ENC_CSN_ID
and CLARITY_ADT.DEPARTMENT_ID = CLARITY_DEP.DEPARTMENT_ID
and CLARITY_DEP.REV_LOC_ID = CLARITY_LOC.LOC_ID
and PAT_ENC_HSP.PAT_ID = V_PAT_FACT.PAT_ID
and ORDER_PROC.AUTHRZING_PROV_ID = CLARITY_SER.PROV_ID
and PAT_ENC_HSP. HOSP_ADMSN_TIME between #StartDate and #EndDate
AND CL_PRL_SS.PROTOCOL_ID = 799
AND CAST(CL_QQUEST.QUEST_ID as varchar(25)) = '101960'
) as preOSU_Data
--********************************************************
-- PATIENT_RACE has multiple lines for some patients
-- Added the following to return Line 1 from Patient_Race
Inner Join(
SELECT DISTINCT
PATIENT_RACE.PAT_ID,
ZC_PATIENT_RACE.NAME as PatRace
FROM PATIENT_RACE, ZC_PATIENT_RACE
WHERE
PATIENT_RACE.PATIENT_RACE_C = ZC_PATIENT_RACE.PATIENT_RACE_C
and LINE = 1
) as Race on preOSU_Data.PAT_ID = Race.PAT_ID
WHERE preOSU_Data.OrderDate = Last_DailyTFGoalTimestamp
-- ORDER BY
-- preOSU_Data.OSU_CSN
-- ,preOSU_Data.OrderDate
) as OSU_Data
--********************************************************
-- PATIENT_RACE has multiple lines for some patients
-- Added the following to return Line 1 from Patient_Race
Inner Join(
SELECT DISTINCT
PATIENT_RACE.PAT_ID,
ZC_PATIENT_RACE.NAME as PatRace
FROM PATIENT_RACE, ZC_PATIENT_RACE
WHERE
PATIENT_RACE.PATIENT_RACE_C = ZC_PATIENT_RACE.PATIENT_RACE_C
and LINE = 1
) as Race on OSU_Data.PAT_ID = Race.PAT_ID
-- WHERE
-- OSU_Data.OrderDate = OSU_Data.Last_DailyTFGoalTimestamp
--
---------------------------------------------------------
-- Daily TF given
---------------------------------------------------------
Inner join
(
select distinct
PATIENT.PAT_NAME,
PAT_ENC.HOSP_DISCHRG_TIME,
pat_enc.pat_enc_csn_id,
IP_FLWSHT_MEAS.recorded_time as TF_Datetime,
CONVERT (DATE,IP_FLWSHT_MEAS.recorded_time) as TF_Date,
Format(IP_FLWSHT_MEAS.recorded_time, 'h:mm tt') as TF_Time,
DATEPART(HOUR, IP_FLWSHT_MEAS.recorded_time) as TF_Hour,
isnull(cast(IP_FLWSHT_MEAS.MEAS_VALUE as float),0) as TF_Daily
FROM
PAT_ENC
LEFT OUTER JOIN PATIENT ON PAT_ENC.PAT_ID = PATIENT.PAT_ID
LEFT OUTER JOIN PAT_ENC_2 ON PAT_ENC.PAT_ENC_CSN_ID = PAT_ENC_2.PAT_ENC_CSN_ID
LEFT OUTER JOIN ZC_PAT_CLASS ON PAT_ENC_2.ADT_PAT_CLASS_C = ZC_PAT_CLASS.ADT_PAT_CLASS_C
LEFT OUTER JOIN IP_FLWSHT_REC ON PAT_ENC.INPATIENT_DATA_ID = IP_FLWSHT_REC.INPATIENT_DATA_ID
LEFT OUTER JOIN IP_FLWSHT_MEAS ON IP_FLWSHT_REC.FSD_ID = IP_FLWSHT_MEAS.FSD_ID
where
PAT_ENC. HOSP_ADMSN_TIME between #StartDate and #EndDate
and IP_FLWSHT_MEAS.FLO_MEAS_ID = '3043040002'
-- and IP_FLWSHT_MEAS.FLT
Group by
PATIENT.PAT_NAME,
PAT_ENC.HOSP_DISCHRG_TIME,
PAT_ENC_2.ADT_PAT_CLASS_C,
pat_enc.pat_enc_csn_id,
IP_FLWSHT_MEAS.recorded_time,
IP_FLWSHT_MEAS.MEAS_VALUE
) as TF_Daily on OSU_Data.OSU_CSN = TF_Daily.pat_enc_csn_id and TF_Datetime > OSU_Data.OrderDate -- and Osu_Data.TF_GoalHr = TF_Daily.TF_Hour
--**********************************************************
--and TF_Daily.TF_Datetime >=
Group by
OSU_Data.OSU_CSN
,OSU_Data.OrderDate
,OSU_Data.DATE_USED
,TF_Datetime
,OSU_Data.LOCATION_ABBR
,OSU_Data.PROTOCOL_NAME
,OSU_Data.PROV_NAME
,OSU_Data.MRN
,OSU_Data.PAT_NAME
,OSU_Data.AGE_YEARS,
OSU_Data.gender,
Race.PatRace,
-- OSU_Data.Race,
OSU_Data.HOSP_ADMSN_TIME,
OSU_Data.HOSP_DISCH_TIME
,TF_Daily.TF_Date
,TF_Daily.TF_Daily
--,TF_Daily2
,TF_Daily.TF_Time
,TF_Daily.TF_Hour
,OSU_Data.TF_ORDERED
) as results
-- Exclusions and Clean-up
Where
results.Total_Required >= 800
and results.Daily_TF_Total > 0

SQL Server : WHERE clause case with between

I have a script which I want to extract values from db accordingly with some dates.
I have a function which return a date, this date can be currentDate - 1 month, or can be curentDate -2 months. The function is
set #syssDate = DATEADD(month, -1, #syss_date);
and I have declared a start date:
declare #start_quarter datetime
set #start_quarter = '2015-07-01';
All I want in my WHERE clause to add a
case
when syssDate = start_quarter
then bu.date between '2015-01-01' and '2015-10-01'
else -- another date
My query looks like:
declare #start_quarter datetime
set #start_quarter = '2015-01-01';
declare #actual_Date datetime
set #actual_Date = DATEADD(month, -1, #rollover_date);
select sum(t.Revenue) as Revenue from (
select sum(bu.value) as Revenue
from bus_category_for bu
join bus_category buc on buc.id=bu.bus_category_id
join bus bu on bu.id=buc.bus_id
where buc.type_id=18 and bu.id=21 and
--Here I want to add a case statement
bu.date between '2015-01-01' and '2015-10-01'
I Guess you need something like this
SELECT Sum(t.Revenue) AS Revenue
FROM (SELECT Sum(bu.value) AS Revenue
FROM bus_category_for bu
JOIN bus_category buc
ON buc.id = bu.bus_category_id
JOIN bus bu
ON bu.id = buc.bus_id
WHERE buc.type_id = 18
AND bu.id = 21
AND ( ( #syssDate = #start_quarter
AND bu.date BETWEEN '2015-01-01' AND '2015-10-01' )
OR ( another date ) ))a
Try something like
WHERE (syssDate = start_quarter AND bu.date between '2015-01-01' and '2015-10-01')
OR (yssDate <> start_quarter AND bu.date between '2016-01-01' and '2016-10-01')
Generally, it's advisable not to use between for dates. It's better to use bu.date >= '2015-01-01' AND bu.date < '2015-10-02'. See here.