In Teradata, SQL Code to count the number of Emergency Visits within 30 days of leaving a hospital - count

I have been asked to summarize the counts, by patients, of how many times they visited the emergency room within 30 days of leaving the hospital. I can do a basic SQL query and export to Excel and toss to pivot after doing some manual calculations, but I was wondering if can be all written in SQL?
The basic query is such:
SELECT Patient_ID, Record#, Site, Admit_Date, Discharge_Date
FROM Admissions
WHERE Admit_Date BETWEEN '2019-01-01' AND '2019-12-31'
I would like to be able to SUM only on rows where [Site] = 'Hospital' of only visits to the ER within 30 days of leaving the hospital within the query to generate two additional columns:
AS "Days Since Hospital Discharge"
AS "ER Visits Within 30 Days After Hospital Discharge and Until Next Hospital Admit"
The output could look like this:
Sample Results
I have Googled and search quite a bit and I cannot find answers where I can combine several solutions. I think I may have to do at least two subqueries, but not sure where to embed it. Any advice would be appreciated. Thank you!

You need nested OLAP-functions, this should return the expected result:
SELECT dt.*
,CASE
WHEN site = 'Hospital'
THEN Count(CASE WHEN site = 'ER' AND "Days Since Hospital Discharge" <= 30 THEN 1 END)
Over (PARTITION BY Patient_ID
ORDER BY Discharge_Date, Admit_Date
RESET WHEN site = 'Hospital')
END AS "ER Visits Within 30 Days After Hospital Discharge and Until Next Hospital Admit"
FROM
(
SELECT Patient_ID, Record#, Site, Admit_Date, Discharge_Date
,CASE
WHEN site <> 'Hospital'
THEN Admit_Date -
-- the previous discharge date
Max(CASE WHEN site = 'Hospital' THEN Discharge_Date END)
Over (PARTITION BY Patient_ID
ORDER BY Discharge_Date, Admit_Date
ROWS Unbounded Preceding)
END AS "Days Since Hospital Discharge"
FROM Admissions
WHERE Admit_Date BETWEEN DATE '2019-01-01' AND DATE '2019-12-31'
) AS dt
Btw, it's easier to help if the data is provided as Create Table + Inserts instead of a jpeg

Related

Average temperature by day of year with SQLite DDB

I'm looking for a good solution to show the average temperature day by day of the year from a SQLite Database.
In my database, to be sample, I have a date column and a temp column, for each day since 5 years like that.
example
I would like to get, for each day of the year, the average temperature from my database.
I found the request to calculate the average for one day, but I don't how can I do like that for each day
SELECT avg(min) FROM historique WHERE strftime('%m-%d', date )= "04-01";
Could you help me please ?
You must use use GROUP BY:
SELECT strftime('%m-%d', date) day, avg(min)
FROM historique
GROUP BY day

SQL does not show me the time (hour by day)

SQL does not show me the time, I have a business day table, and I need that for each business day it shows me a time range from 9 to 19 hours to then show the number of transactions per hour, for each day of the month.
I can not generate stored procedure only query can be performed not to alter the database by company policy
I have a query like that.
SELECT
TO_CHAR(cd.days, 'yyyymmdd') AS fechaTransaccion,
NVL(SUM(data.numTransacionExitosa),0) AS numTransacionExitosa,
NVL(SUM(data.numTransactionPendiente),0) AS numTransactionPendiente
FROM
calendardays cd
LEFT JOIN
data
ON
cd.days = data.settledate
WHERE
cd.DAYs BETWEEN ADD_MONTHS(TRUNC(to_date(20200201, 'yyyymmdd'), 'MM'),-1) AND ADD_MONTHS(LAST_DAY(TRUNC(to_date(20200201, 'yyyymmdd'))),-1)
and substr(SETTLEDATE, 10, 2) between 9 and 19
GROUP BY
cd.days, substr(SETTLEDATE, 10, 2)
ORDER BY
cd.days
i need show like this
Hard to understand/answer without seeing your data, but if you need to extract hour from date, follow the below example:
select extract(hour from cast(sysdate as timestamp)) hour from dual;

Informatica: How to pick the sorted record from multiple rows or take the max on two columns together in Informatica

I have a requirement as below.
source:
prod_id DATE Price Count(Price)
1 01-02-2017 100 1
1 01-02-2017 10 4
2 02-02-2017 50 1
2 02-02-2017 60 1
I have data like this. Now I need to pick records with max(count(Price)) for every unique prod_id and date combination, but if Count(price) is same then it should take max(price) or sort the columns on the basis of Count(price) and price and pick the top record. I'm achieving this data by using an aggregator doing group by prod_id, date column and taking count on price and not a direct table. How can I achieve this? Any suggestions?
Thanks,
Priyanka
Sort the records based on Count(Price) and Price in that order and use an aggregator with prod_id and date as key. Do not use any aggregate function. The aggregator will pass the last record for each group.
As you tagged Teradata, you can get it directly by adding
select .....
qualify
row_number()
over(partition by prod_id
order by Count(Price) desc, Price desc) = 1
to your current query.

Apache Drill: Group by week

I tried to group my daily data by week (given a reference date) to generate a smaller panel data set.
I used postgres before and there it was quite easy:
CREATE TABLE videos_weekly AS SELECT channel_id,
CEIL(DATE_PART('day', observation_date - '2016-02-10')/7) AS week
FROM videos GROUP BY channel_id, week;
But it seems like it is not possible to subtract a timestamp with a date string in Drill. I found the AGE function, which returns an interval between two dates, but how to convert this into an integer (number of days or weeks)?
DATE_SUB may help you here. Following is an example:
SELECT extract(day from date_sub('2016-11-13', cast('2015-01-01' as timestamp)))/7 FROM (VALUES(1));
This will return number of weeks between 2015-01-01 and 2016-11-13.
Click here for documentation

Selecting Rows with based on Count (SQLite)

Hoping for some help with this:
1) I am trying to select all calls (rows) for CustomerIDs that show up 6 or more times within a 30 day rolling period, so if the CustomerID is within the file 6 or more times within 30 days, then it would provide me with all records for that CustomerID.
2) I also need to select all calls for CustomerIDs that show up 2 or more times within a 30 day rolling period but ONLY if two certain columns also match (CallType1 and CallType2). Very similar to the query with the 6 calls but we need to consider that the call types are exactly the same too.
SELECT * FROM tablename
WHERE CustomerID IN (SELECT CustomerID FROM tablename
WHERE "CustomerID"
IN ('MyProgram'));
The query above selects all of the CustomerIDs which reach my program. I need to add the logic to count >=6 CustomerIDs (item 1 above) and then a second query to get the >=2 with the same CallTypes.
The innermost subquery computes how many calls there are in the window beginning at First.
The middle subquery checks this value for every possible window in the table. (This is inefficient, but SQLite has no window functions.)
SELECT *
FROM TableName
WHERE CustomerID IN (SELECT CustomerID
FROM TableName AS First
WHERE (SELECT COUNT(*)
FROM TableName
WHERE Date BETWEEN First.Date
AND date(First.Date, '+30 days')
AND CustomerID = First.CustomerID
) >= 6)
This assumes that there is a column Date using the default date format (yyyy-mm-dd).

Resources