Select where no value is greater than X - sql

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

Related

How could I join these queries together?

I have 2 queries. One includes a subquery and the other is a pretty basic query. I can't figure out how to combine them to return a table with name, workdate, minutes_inactive, and hoursworked.
I have the code below for what I have tried. The simple query is lines 1,2, and the last 5 lines. I also added a join clause (join punchclock p on p.servrepID = l.repid) to it.
Both these queries ran on their own so this is solely just the problem of combining them.
select
sr.sr_name as liaison, cast(date_created as date) workdate,
(count(date_created) * 4) as minutes_inactive,
(select
sr_name, cast(punchintime as date) as workdate,
round(sum(cast(datediff(minute,punchintime, punchouttime) as real) / 60), 2) as hoursworked,
count(*) as punches
from
(select
sr_name, punchintime = punchdatetime,
punchouttime = isnull((select top 1 pc2.punchdatetime
from punchclock pc2
where pc2.punchdatetime > pc.punchdatetime
and pc.servrepid = pc2.servrepid
and pc2.inout = 0
order by pc2.punchdatetime), getdate())
from
punchclock pc
join
servicereps sr on pc.servrepid = sr.servrepid
where
punchyear >= 2017 and pc.inout = 1
group by
sr_name, cast(punchintime as date)))
from
tbl_liga_popup_log l
join
servicereps sr on sr.servrepID = l.repid
join
punchclock p on p.servrepID = l.repid collate latin1_general_bin
group by
cast(l.date_created as date), sr.sr_name
I get this error:
Msg 102, Level 15, State 1, Line 19
Incorrect syntax near ')'
I keep getting this error but there are more errors if I adjust that part.
I don't know that we'll fix everything here, but there are a few issues with your query.
You have to alias your sub-query (technically a derived table, but whatever)
You have two froms in your outer query.
You have to join to the derived table.
Here's an crude example:
select
<some stuff>
from
(select col1 from table1) t1
inner join t2
on t1.col1 = t2.col2
The large error here is that you are placing queries in the select section (before the from). You can only do this if the query returns a single value. Else, you have to put your query in a parenthesis (you have done this) in the from section, give it an alias, and join it accordingly.
You also seem to be using group bys that are not needed anywhere. I can't see aggregation functions like sum().
My best bet is that you are looking for the following query:
select
sr_name as liaison
,cast(date_created as date) workdate
,count(distinct date_created) * 4 as minutes_inactive
,cast(punchintime as date) as workdate
,round(sum(cast(datediff(minute,punchintime,isnull(pc2_query.punchouttime,getdate())) as real) / 60), 2) as hoursworked
,count(*) as punches
from
punchclock pc
inner join servicereps sr on pc.servrepid = sr.servrepid
cross apply
(
select top 1 pc2.punchdatetime as punchouttime
from punchclock pc2
where pc2.punchdatetime > pc.punchdatetime
and pc.servrepid = pc2.servrepid
and pc2.inout = 0
order by pc2.punchdatetime
)q1
inner join tbl_liga_popup_log l on sr.servrepID = l.repid
where punchyear >= 2017 and pc.inout = 1

How to force postgres to return 0 even if there are no rows matching query, using coalesce, group by and join

I've been trying hopelessly to get the following SQL statement to return the query results and default to 0 if there are no rows matching the query.
This is the intended result:
vol | year
-------+------
0 | 2018
Instead I get:
vol | year
-----+------
(0 rows)
Here is the sql statement:
select coalesce(vol,0) as vol, year
from (select sum(vol) as vol, year
from schema.fact_data
join schema.period_data
on schema.fact_data.period_tag = schema.period_data.tag
join schema.product_data
on schema.fact_data.product_tag =
schema.product_data.tag
join schema.market_data
on schema.fact_data.market_tag = schema.market_data.tag
where "retailer"='MadeUpRetailer'
and "product_tag"='FakeProductTag'
and "year"='2018' group by year
) as DerivedTable;
I know the query works because it returns data when there is data. Just doesn't default to 0 as intended...
Any help in finding why this is the case would be much appreciated!
Using your subquery DerivedTable, you could write:
SELECT coalesce(DerivedTable.vol, 0) AS vol,
y.year
FROM (VALUES ('2018'::text)) AS y(year)
LEFT JOIN (SELECT ...) AS DerivedTable
ON DerivedTable.year = y.year;
Remove the GROUP BY (and the outer query):
select 2018 as year, coalesce(sum(vol), 0) as vol
from schema.fact_data f join
schema.period_data p
on f.period_tag = p.tag join
schema.product_data pr
on f.product_tag = pr.tag join
schema.market_data m
on fd.market_tag = m.tag
where "retailer" = 'MadeUpRetailer' and
"product_tag" = 'FakeProductTag' and
"year" = '2018';
An aggregation query with no GROUP BY always returns exactly one row, so this should do what you want.
EDIT:
The query would look something like this:
select v.yyyy as year, coalesce(sum(vol), 0) as vol
from (values (2018), (2019)) v(yyyy) left join
schema.fact_data f
on f.year = v.yyyy left join -- this is just an example. I have no idea where year is coming from
schema.period_data p
on f.period_tag = p.tag left join
schema.product_data pr
on f.product_tag = pr.tag left join
schema.market_data m
on fd.market_tag = m.tag
group by v.yyyy
However, you have to move the where conditions to the appropriate on clauses. I have no idea where the columns are coming from.
From the code you posted it is not clear in which table you have the year column.
You can use UNION to fetch just 1 row in case there are no rows in that table for the year 2018 like this:
select sum(vol) as vol, year
from schema.fact_data innrt join schema.period_data
on schema.fact_data.period_tag = schema.period_data.tag
inner join schema.product_data
on schema.fact_data.product_tag = schema.product_data.tag
inner join schema.market_data
on schema.fact_data.market_tag = schema.market_data.tag
where
"retailer"='MadeUpRetailer' and
"product_tag"='FakeProductTag' and
"year"='2018'
group by "year"
union
select 0 as vol, '2018' as year
where not exists (
select 1 from tablename where "year" = '2018'
)
In case there are rows for the year 2018, then nothing will be fetched by the 2nd query,

Select Latest or most recent date in SQL query

I am running a query in SQL on our EHR/EMR database. I am primarily looking at an assessment that is done by a nurse during each patient encounter/visit and looking to return an answer for the most recent assessment date along with some other info. I have the query created and all the data is coming over, however, it is returning all assessment dates and the answers instead of just the latest date and answer. I'll attach the full code below.
SELECT DISTINCT
MAX(PTA.ASSESSMENT_DATE) AS Max_Date,
SAQ.QUESTION_TEXT, SAA.ANSWER_TEXT, dbo.PT_BASIC.PATIENT_CODE,
dbo.PT_BASIC.NAME_FULL
FROM
dbo.PTC_ASSESSMENT_ANSWER AS PAA
INNER JOIN
dbo.PTC_ASSESSMENT AS PTA ON PTA.ASSESSMENT_ID = PAA.ASSESSMENT_ID
AND PTA.PATIENT_ID = PAA.PATIENT_ID
INNER JOIN
dbo.SYS_ASSESSMENT_POINTER AS SAP ON SAP.POINTER_ID = PAA.POINTER_ID
INNER JOIN
dbo.SYS_ASSESSMENT_QUESTION AS SAQ ON SAQ.QUESTION_ID = SAP.QUESTION_ID
INNER JOIN
dbo.SYS_ASSESSMENT_ANSWER AS SAA ON SAA.ANSWER_ID = SAP.ANSWER_ID
INNER JOIN
dbo.PT_BASIC ON PTA.PATIENT_ID = dbo.PT_BASIC.PATIENT_ID
WHERE
(PTA.ASSESSMENT_DATE BETWEEN CONVERT(DATETIME, '2017-09-05 00:00:00', 102)
AND CONVERT(DATETIME, '2017-10-12 00:00:00', 102))
GROUP BY
dbo.PT_BASIC.PATIENT_CODE, dbo.PT_BASIC.NAME_FULL, SAQ.QUESTION_TEXT,
SAA.ANSWER_TEXT
HAVING
(SAA.ANSWER_TEXT LIKE '%LEVEL % -%')
The current output would be something similar to this:
9/5/2017 PATIENT ABC Answer1
9/6/2017 PATIENT ABC Answer2
9/7/2017 PATIENT ABC Answer3
9/6/2017 PATIENT XYZ Answer4
What I am expecting is:
9/7/2017 PATIENT ABC Answer3
9/6/2017 PATIENT XYZ Answer4
If your version of SQL Server supports it, using ROW_NUMBER() OVER() is an efficient and simple method for arriving at "latest" (or "earliest") rows from a single table. However as we know so little about your data model it isn't easy to guess how to reduce the rows to just the "lastest answer" which probably requires a more complex subquery. However you can still use ROW_NUMBER() OVER() on that subquery. I suspect that the nature of questions and answers is that the table aliases SAP, SAQ, SAA may all need to be involved in this subquery.
Note that instead of directly joining PTA this is now a subquery and the join condition to the outer query requires that RN=1 which is the row with the "latest" date.
SELECT
MAX(PTA.ASSESSMENT_DATE) AS Max_Date
, SAQ.QUESTION_TEXT
, SAA.ANSWER_TEXT
, dbo.PT_BASIC.PATIENT_CODE
, dbo.PT_BASIC.NAME_FULL
FROM dbo.PTC_ASSESSMENT_ANSWER AS PAA
INNER JOIN (
SELECT
*
, ROW_NUMBER() OVER (PARTITION BY PATIENT_ID
ORDER BY ASSESSMENT_DATE DESC) AS RN
FROM dbo.PTC_ASSESSMENT
WHERE ASSESSMENT_DATE BETWEEN '20170905' AND '20171012'
) AS PTA ON PTA.ASSESSMENT_ID = PAA.ASSESSMENT_ID
AND PTA.PATIENT_ID = PAA.PATIENT_ID
AND PTA.RN = 1
INNER JOIN dbo.SYS_ASSESSMENT_POINTER AS SAP ON SAP.POINTER_ID = PAA.POINTER_ID
INNER JOIN dbo.SYS_ASSESSMENT_QUESTION AS SAQ ON SAQ.QUESTION_ID = SAP.QUESTION_ID
INNER JOIN dbo.SYS_ASSESSMENT_ANSWER AS SAA ON SAA.ANSWER_ID = SAP.ANSWER_ID
INNER JOIN dbo.PT_BASIC ON PTA.PATIENT_ID = dbo.PT_BASIC.PATIENT_ID
WHERE SAA.ANSWER_TEXT LIKE '%LEVEL % -%'
GROUP BY
dbo.PT_BASIC.PATIENT_CODE
, dbo.PT_BASIC.NAME_FULL
, SAQ.QUESTION_TEXT
, SAA.ANSWER_TEXT
select distinct is not required on this query (or any similar query using GROUP BY)
yyymmdd is the safest date literal in SQL Server, you don't need the converts using style 102
your having clause should be moved to a where clause as it does not evaluate any aggregated value
Cross apply allows you to use a correlated query and chive the top most n records ordered by date desc for each patient assessment. (after review maybe you just need patient?)
Perhaps just change:
INNER JOIN
dbo.PTC_ASSESSMENT AS PTA ON PTA.ASSESSMENT_ID = PAA.ASSESSMENT_ID
AND PTA.PATIENT_ID = PAA.PATIENT_ID
TO:
CROSS APPLY (SELECT TOP 1 *
FROM dbo.PTC_ASSESSMENT PTA2
WHERE PTA2.ASSESSMENT_ID = PAA.ASSESSMENT_ID
/*AND PTA2.PATIENT_ID = PAA.PATIENT_ID*/
ORDER BY PTA2.Assessment_date desc) PTA
GIVING YOU: (I left the /AND PTA2.PATIENT_ID = PAA.PATIENT_ID/ --I think you can omit this. I left the */ in place but it's not needed)
SELECT MAX(PTA.ASSESSMENT_DATE) AS Max_Date
, SAQ.QUESTION_TEXT
, SAA.ANSWER_TEXT
, dbo.PT_BASIC.PATIENT_CODE
, dbo.PT_BASIC.NAME_FULL
FROM dbo.PTC_ASSESSMENT_ANSWER AS PAA
CROSS APPLY (SELECT TOP 1 *
FROM dbo.PTC_ASSESSMENT PTA2
WHERE PTA2.ASSESSMENT_ID = PAA.ASSESSMENT_ID --I think you can omit this.
/*AND PTA2.PATIENT_ID = PAA.PATIENT_ID*/
ORDER BY PTA2.Assessment_date desc) PTA
INNER JOIN dbo.SYS_ASSESSMENT_POINTER AS SAP
ON SAP.POINTER_ID = PAA.POINTER_ID
INNER JOIN dbo.SYS_ASSESSMENT_QUESTION AS SAQ
ON SAQ.QUESTION_ID = SAP.QUESTION_ID
INNER JOIN dbo.SYS_ASSESSMENT_ANSWER AS SAA
ON SAA.ANSWER_ID = SAP.ANSWER_ID
INNER JOIN dbo.PT_BASIC
ON PTA.PATIENT_ID = dbo.PT_BASIC.PATIENT_ID
WHERE (PTA.ASSESSMENT_DATE BETWEEN CONVERT(DATETIME, '2017-09-05 00:00:00', 102) AND CONVERT(DATETIME, '2017-10-12 00:00:00', 102))
GROUP BY dbo.PT_BASIC.PATIENT_CODE
, dbo.PT_BASIC.NAME_FULL
, SAQ.QUESTION_TEXT
, SAA.ANSWER_TEXT
HAVING (SAA.ANSWER_TEXT LIKE '%LEVEL % -%')
It appears you're not concerned about patients w/o assessments as all your joins are inner or we could use OUTER APPPLY to be sure to keep all answers regardless if an assessment has been provided.
Alternatively you could use a row_number() logic ( Tab Alleman's link has this covered) and a cte; but if cross apply is available might as well use it here.
Please include order by PTA.ASSESSMENT_DATE DESC to see the latest records at the top.

SQL Query to return 2 results for multiple employees

I am very new to SQL and in fact, I am completely self taught. I currently have this query below which works to find (badly) 2 random support tickets by employee.
Right now, the query will ask the employees name and provide 2 results. Is there a way to have this provide 2 results for ALL employees?
SELECT
TOP 2 CONVERT (
DATE,
SD_REQUEST.END_DATE_UT
) AS 'Close Date',
SD_REQUEST.RFC_number AS 'Ticket',
agent.LAST_NAME AS 'Agent',
AM_DOMAIN.NAME_EN AS 'Company',
EE.LAST_NAME AS 'Recipient',
RR.LAST_NAME AS 'Requestor',
catpath.SD_CATALOG_PATH_EN
FROM
SD_REQUEST
LEFT JOIN AM_EMPLOYEE AS agent ON agent.EMPLOYEE_ID = SD_REQUEST.OWNER_ID
LEFT JOIN AM_EMPLOYEE AS EE ON EE.EMPLOYEE_ID = SD_REQUEST.RECIPIENT_ID
LEFT JOIN AM_EMPLOYEE AS RR ON RR.EMPLOYEE_ID = SD_REQUEST.REQUESTOR_ID
LEFT JOIN SD_CATALOG_PATH AS catpath ON catpath.SD_CATALOG_ID = SD_REQUEST.SD_CATALOG_ID
LEFT JOIN AM_DOMAIN ON AM_DOMAIN.DOMAIN_ID = EE.DEFAULT_DOMAIN_ID
WHERE
agent.LAST_NAME = 'insert name here'
AND CONVERT (
datetime,
SD_REQUEST.END_DATE_UT,
101
) BETWEEN (Getdate() - 8)
AND (Getdate() - 2)
ORDER BY
NEWID()
I'm assuming you're using SQL Server based on syntax in question. You can use the ROW_NUMBER() function inside a cte/subquery to generate a number for each row, using PARTITION BY you can have the numbering start over for each member of a given set/group, in this case agent.LAST_NAME, you can use that number to limit to two results per set/group:
;with cte AS (
SELECT CONVERT (DATE,SD_REQUEST.END_DATE_UT) AS 'Close Date',
SD_REQUEST.RFC_number AS 'Ticket',
agent.LAST_NAME AS 'Agent',
AM_DOMAIN.NAME_EN AS 'Company',
EE.LAST_NAME AS 'Recipient',
RR.LAST_NAME AS 'Requestor',
catpath.SD_CATALOG_PATH_EN,
ROW_NUMBER() OVER(PARTITION BY agent.LAST_NAME ORDER BY NEWID()) AS RN
FROM
SD_REQUEST
LEFT JOIN AM_EMPLOYEE AS agent ON agent.EMPLOYEE_ID = SD_REQUEST.OWNER_ID
LEFT JOIN AM_EMPLOYEE AS EE ON EE.EMPLOYEE_ID = SD_REQUEST.RECIPIENT_ID
LEFT JOIN AM_EMPLOYEE AS RR ON RR.EMPLOYEE_ID = SD_REQUEST.REQUESTOR_ID
LEFT JOIN SD_CATALOG_PATH AS catpath ON catpath.SD_CATALOG_ID = SD_REQUEST.SD_CATALOG_ID
LEFT JOIN AM_DOMAIN ON AM_DOMAIN.DOMAIN_ID = EE.DEFAULT_DOMAIN_ID
WHERE CONVERT (datetime,SD_REQUEST.END_DATE_UT,101) BETWEEN (Getdate() - 8) AND (Getdate() - 2)
)
SELECT *
FROM cte
WHERE RN <= 2

SQL UNION query not working

here is my current queries:
1
SELECT FilteredInvoice.accountidname,
FilteredInvoice.createdon,
FilteredInvoice.createdon AS sort_date,
FilteredInvoice.duedate,
FilteredInvoice.invoicenumber,
FilteredInvoice.statecodename,
FilteredInvoice.totalamount_base,
CONVERT(datetime, NULL) AS mag_paymentdate,
0 AS mag_amount_base,
GETDATE() AS Today
FROM FilteredAccount AS CRMAF_FilteredAccount
JOIN FilteredInvoice ON FilteredInvoice.accountid = CRMAF_FilteredAccount.accountid
JOIN FilteredMag_Payment ON FilteredInvoice.invoiceid = FilteredMag_Payment.mag_invoiceid
WHERE (FilteredInvoice.statecodename <> 'Canceled')
2
SELECT FilteredInvoice_1.accountidname,
FilteredInvoice_1.createdon,
FilteredInvoice_1.createdon AS sort_date,
FilteredInvoice_1.duedate,
FilteredInvoice_1.invoicenumber,
FilteredInvoice_1.statecodename,
FilteredInvoice_1.totalamount_base,
FilteredMag_Payment.mag_paymentdate,
FilteredMag_Payment.mag_amount_base,
GETDATE() AS Today
FROM FilteredAccount AS CRMAF_FilteredAccount
LEFT JOIN FilteredInvoice AS FilteredInvoice_1 ON FilteredInvoice_1.accountid = CRMAF_FilteredAccount.accountid
JOIN FilteredMag_Payment ON FilteredInvoice_1.invoiceid = FilteredMag_Payment.mag_invoiceid
WHERE (FilteredInvoice_1.statecodename <> 'Canceled')
These alone do exactly what i am wanting them to but as soon as i try and join them using a "UNION" or "Sub-query" the second query always breaks and displays the wrong information.
Am I just being blond not being able to work this out or am I actually doing something wrong.
All help is appreciated.
Many thanks Simon.
EDIT:
What I mean by "Wrong information" is that the 2nd query is returning all values rather then following the CRMAF_ prefix and returning only values from the account it is run on.
It's hard to guess what do you mean by "wrong information" but I believe you want UNION ALL rather than UNION.
UNION removes duplicates so the records from the second query won't be returned if they were previously returned by the first query. In addition, the possible duplicates within one query will be eliminated too.
The number of records in a UNION can be less than the total count of records in two queries.
If you just want to concatenate two recordsets, use UNION ALL:
SELECT FilteredInvoice.accountidname,
FilteredInvoice.createdon,
FilteredInvoice.createdon AS sort_date,
FilteredInvoice.duedate,
FilteredInvoice.invoicenumber,
FilteredInvoice.statecodename,
FilteredInvoice.totalamount_base,
CONVERT(datetime, NULL) AS mag_paymentdate,
0 AS mag_amount_base,
GETDATE() AS Today
FROM FilteredAccount AS CRMAF_FilteredAccount
JOIN FilteredInvoice ON FilteredInvoice.accountid = CRMAF_FilteredAccount.accountid
JOIN FilteredMag_Payment ON FilteredInvoice.invoiceid = FilteredMag_Payment.mag_invoiceid
WHERE (FilteredInvoice.statecodename <> 'Canceled')
UNION ALL
SELECT FilteredInvoice_1.accountidname,
FilteredInvoice_1.createdon,
FilteredInvoice_1.createdon AS sort_date,
FilteredInvoice_1.duedate,
FilteredInvoice_1.invoicenumber,
FilteredInvoice_1.statecodename,
FilteredInvoice_1.totalamount_base,
FilteredMag_Payment.mag_paymentdate,
FilteredMag_Payment.mag_amount_base,
GETDATE() AS Today
FROM FilteredAccount AS CRMAF_FilteredAccount
LEFT JOIN FilteredInvoice AS FilteredInvoice_1 ON FilteredInvoice_1.accountid = CRMAF_FilteredAccount.accountid
JOIN FilteredMag_Payment ON FilteredInvoice_1.invoiceid = FilteredMag_Payment.mag_invoiceid
WHERE (FilteredInvoice_1.statecodename <> 'Canceled')
It looks to me as though you should be able to get the same results as you would from the UNIONed query, with the following:
SELECT FilteredInvoice_1.accountidname,
FilteredInvoice_1.createdon,
FilteredInvoice_1.createdon AS sort_date,
FilteredInvoice_1.duedate,
FilteredInvoice_1.invoicenumber,
FilteredInvoice_1.statecodename,
FilteredInvoice_1.totalamount_base,
CASE PF.pay_flag
WHEN 0.0 THEN CONVERT(datetime, NULL)
ELSE FilteredMag_Payment.mag_paymentdate
END AS mag_paymentdate,
FilteredMag_Payment.mag_amount_base * PF.pay_flag AS mag_amount_base,
GETDATE() AS Today
FROM FilteredAccount AS CRMAF_FilteredAccount
CROSS JOIN (SELECT 1.0 pay_flag UNION SELECT 0.0) AS PF
JOIN FilteredInvoice AS FilteredInvoice_1 ON FilteredInvoice_1.accountid = CRMAF_FilteredAccount.accountid
LEFT JOIN FilteredMag_Payment ON FilteredInvoice_1.invoiceid = FilteredMag_Payment.mag_invoiceid
WHERE (FilteredInvoice_1.statecodename <> 'Canceled') AND
(PF.pay_flag = 0 OR FilteredMag_Payment.mag_invoiceid IS NOT NULL)
EDIT: LEFT JOIN FilteredMag_Payment
FURTHER EDIT: added final parenthesised OR condition to WHERE clause.