PostgreSQL: How to join two tables using between date? - sql

I really don't know how to ask this question of mine.
I'll illustrate it using two tables I needed to join.
TABLE_1
Name Date
John 01-01-2016
May 04-08-2015
Rose 10-25-2016
Mary 12-15-2015
Ruby 07-07-2017
TABLE_2
Signatory DateFrom DateTo
President 1 01-01-2015 12-31-2015
President 2 01-01-2016 12-31-2016
RESULT:
Name Date Signatory
John 01-01-2016 President 2
May 04-08-2015 President 1
Rose 10-25-2016 President 2
Mary 12-15-2015 President 1
Ruby 07-07-2017 NULL
All I need to check if the Date of Table_1 is within the DateFrom and DateTo of Table_2 to get the Signatory field.
How I can do that?
Thanks a lot! ^_^

Try this:
SELECT t1.*, t2.Signatory
FROM Table_1 AS t1
LEFT JOIN Table_2 AS t2
ON t1."Date" BETWEEN t2.DateFrom AND t2.DateTo
What you need is just a LEFT JOIN with BETWEEN in the ON clause in order to determine whether Date field of Table_1 falls within any [DateFrom, DateTo] interval of Table_2.
Demo here

Related

How to substract between same date/time DB column in Oracle

Oracle SQL In the table there are status given to the each row(arrived, ExamCompleted, VitalsTaken, discharged...)where we track information about patients in the hospital. It is required to find the number of hours patient spent inside the hospital. How can I substract one column with itself where status are different.
patient_id | status | created_on
7654 | arrived | 2022-09-18 07:22:46
7654 | examCompleted | 2022-09-18 09:35:26
7654 | vitalsTaken | 2022-09-20 02:41:55
7654 | discharged | 2022-09-20 07:42:33
I need to substract arrived status date/time from discharged status date/time Table have many other columns but these are the ones I need to work with. If there are null recorded for a created_on column (for few rows) how can I ignore that particular row while showing data.
Desired result is something like
patient_id | timeSpent
7654 | 48:19:13
Thank you in advance
Do a self join on the database table. The total time would be the value of column CREATED_ON when the STATUS is discharged minus the value of CREATED_ON when the STATUS is arrived for a given PATIENT_ID. The below SQL gives the result as a number of hours.
select A.PATIENT_ID
,(B.CREATED_ON - A.CREATED_ON) * 24 as STAY
from PATIENTS A
join PATIENTS B
on A.PATIENT_ID = B.PATIENT_ID
where A.STATUS = 'arrived'
and B.STATUS = 'discharged'
Refer to this db<>fiddle
Also refer to: https://asktom.oracle.com/Misc/DateDiff.html
Correct?? That what you expected?
SELECT DISTINCT patient_id,
MAX(created_on) OVER(PARTITION BY patient_id) - MIN(created_on) OVER(PARTITION BY patient_id)
FROM PATIENTS

How to count by two fields and join with other table Postgres?

I have two tables, one table user and second table transactions related with the transactions done by a user. I want to do a query that give me the count by name and date, with the fields in user table. How can I do it?
Table user:
Name Id Card
-----------------
Alex 01 N
James 02 Y
Table transaction:
Name Date
-----------------
Alex 01/07/2012
Alex 01/12/2012
James 01/08/2012
Alex 01/07/2012
Alex 01/12/2012
James 01/07/2012
James 01/07/2012
I want sometihng like this:
Name Date Transactions ID Card
---------------------------------------------
Alex 01/07/2012 2 01 N
Alex 01/12/2012 2 01 N
James 01/08/2012 1 02 Y
James 01/07/2012 2 02 Y
First of all I tryed to count by two columns with something like this:
select name, date, count(name, date) from pm_transaction GROUP BY (name,date)
select count(distinct(machine, date)) from pm_transaction
But it does not work, I tried a lot of combinations but no one works
Try this
select tb1.name, tb2.date , tb2.transaction , tb1.Id, tb1.card
from tbUser as tb1
inner join
(select date,
name,
count(date) as transaction
from tbTransaction group by date)
as tb2 on tb1.name = tb2.name
This looks like simple aggregation task. Just check and correct table join condition and table names:
select u.name, t.date, count(1) as transactions, u.id, u.card
from transaction t
join user_table u on u.name = t.name
group by u.name, t.date, u.id, u.card;

Aggregate operation oracle

I have two tables and I need to find the person with the highest value.
TABLE1
NAME ID
--------------- ---------------
MIKE 101
MIKE 102
BETTY 103
BETTY 104
BETTY 105
TIM 106
TABLE2
ID VALUE
-------- --------------
101 12
102 10
103 20
104 20
105 10
106 5
I can write a select statement that will give a result of name and values:
SELECT name, value
FROM table1, table2
WHERE table1.id = table.id;
NAME VALUE
----- ----------
MIKE 12
MIKE 10
BETTY 20
BETTY 20
BETTY 10
TIM 5
Now I need to aggregate the values of the rows with equal names and I can not figure it out. Am I going about it the correct way?
Please try this :
select a.name,max(b.value) as value
from table1 a
inner join table2 b on a.id = b.id
group by a.name
Anyway, you tagged mysql and oracle in the question. Luckily, this sql works in both. But you have to remove one of these two tags, to make sure which dbms are you use.
Use this.. and since your column names are unique, you don't need any alias.
select name, max(value) as MaxValue
from table1
inner join table2 on table1.id = table2.id
group by name

Retrieve all distinct records from table and if any changes happen between two similar distinct record then need to consider both. Using select query

I want to convert table1 into table2. As I need to find out all distinct records excluding mis_date fro the table and most important condition is if any changes happen between two similar distinct records than in that case I want both of them as two distinct records.
Example:
i/p
empId Empname Pancard MisDate
123 alex ads234 31/11/2012
123 alex ads234 31/12/2012
123 alex ads234 31/01/2013
123 alex dds124 29/02/2013
123 alex ads234 31/03/2013
123 alex ads234 31/04/2013
123 alex dds124 30/05/2013
Expected o/p
empId Empname Pancard MisDate
123 alex ads234 31/11/2012
123 alex dds124 29/02/2013
123 alex ads234 31/03/2013
123 alex dds124 30/05/2013
Assuming there's only one row for each MisDate (otherwise you'll have to find another way to specify ordering):
SELECT t1.empId, t1.Empname, t1.Pancard
FROM Table1 t1
LEFT OUTER JOIN Table1 t2
ON t2.MisDate = (SELECT MAX(MisDate) FROM Table1 t3 WHERE t3.MisDate < t1.MisDate)
WHERE t2.empId IS NULL
OR t2.empId <> t1.empId OR t2.Empname <> t1.Empname OR t2.Pancard <> t1.Pancard
SQL Fiddle example
This performs a self-join on the previous record, as ordered by MisDate, outputting if it is different or if there is no previous record (it is the first row).
Note: You've got some funky dates. I assume these are just transcription errors and have corrected them in the fiddle.

SQL Join Ignore multiple matches (fuzzy results ok)

I don't even know what the name of my problem is called, so I'm just gonna put some sample data. I don't mind fuzzy results on this (this is the best way I can think to express it. I don't mind if I overlook some data, this is for approximated evaluation, not for detailed accounting, if that makes sense). But I do need every record in TABLE 1, and I would like to avoid the nulls case indicated below.
IS THIS POSSIBLE?
TABLE 1
acctnum sub fname lname phone
12345 1 john doe xxx-xxx-xxxx
12346 0 jane doe xxx-xxx-xxxx
12347 0 rob roy xxx-xxx-xxxx
12348 0 paul smith xxx-xxx-xxxx
TABLE 2
acctnum sub division
12345 1 EAST
12345 2 WEST
12345 3 NORTH
12346 1 TOP
12346 2 BOTTOM
12347 2 BALLOON
12348 1 NORTH
So if we do a "regular outer" join, we'd get some results like this, since the sub 0's don't match the second table:
TABLE AFTER JOIN
acctnum sub fname lname phone division
12345 1 john doe xxx-xxx-xxxx EAST
12346 0 jane doe xxx-xxx-xxxx null
12347 0 rob roy xxx-xxx-xxxx null
12348 0 paul smith xxx-xxx-xxxx null
But I would rather get
TABLE AFTER JOIN
acctnum sub fname lname phone division
12345 1 john doe xxx-xxx-xxxx EAST
12346 0 jane doe xxx-xxx-xxxx TOP
12347 0 rob roy xxx-xxx-xxxx BALLOON
12348 0 paul smith xxx-xxx-xxxx NORTH
And I'm trying to avoid:
TABLE AFTER JOIN
acctnum sub fname lname phone division
12345 1 john doe xxx-xxx-xxxx EAST
12345 1 john doe xxx-xxx-xxxx WEST
12345 1 john doe xxx-xxx-xxxx NORTH
12346 0 jane doe xxx-xxx-xxxx TOP
12346 0 jane doe xxx-xxx-xxxx BOTTOM
12347 0 rob roy xxx-xxx-xxxx BALOON
12348 0 paul smith xxx-xxx-xxxx NORTH
So I decided to go with using a union and two if conditions. I'll accept a null for conditions where the sub account is defined in table 1 but not in table 2, and for everything else, I'll just match against the min.
If I'm understanding correctly, it looks like you're trying to join on the sub column if it matches. If there's no match on sub, then you want it to select the "first" row for that acctnum. Is this correct?
If so, you'll need to left join on the full match, then perform another left join on a select statement that determines the division that corresponds to the lowest sub value for that acctnum. The row_number() function can help you with this, like this:
select
t1.acctnum,
t1.sub,
t1.fname,
t1.lname,
t1.phone,
isnull(t2_match.division, t2_first.division) as division
from table1 t1
left join table2 t2_match on t2_match.acctnum = t1.acctnum and t2_match.sub = t1.sub
left join
(
select
acctnum,
sub,
division,
row_number() over (partition by acctnum order by sub) as rownum
from table2
) t2_first on t2_first.acctnum = t1.acctnum
EDIT
If you don't care at all about which record you get back from table 2 when a matching sub doesn't exist, you could combine two different queries (one that matches the sub and one that just takes the min or max division) with a union.
select
t1.acctnum,
t1.sub,
t1.fname,
t1.lname,
t1.phone,
t2.division
from table1 t1
join table2 t2 on t2.acctnum = t1.acctnum and t2.sub = t1.sub
union
select
t1.acctnum,
t1.sub,
t1.fname,
t1.lname,
t1.phone,
min(t2.division)
from table1 t1
join table2 t2 on t2.acctnum = t1.acctnum
left join table2 t2_match on t2_match.acctnum = t1.acctnum and t2_match.sub = t1.sub
where t2_match.acctnum is null
Personally, I don't find the union syntax any more compelling and you now have to maintain the query in two places. For this reason, I'd favor the row_number() approach.
try to use
SELECT MIN(Table_1.acctnum) as acctnum , MIN(Table_1.sub) as sub,MIN( Table_1.fname) as fname, MIN(Table_1.lname) as name, MIN(Table_1.phone) as phone, MIN(Table_2.division) as division
FROM Table_1 INNER JOIN Table_2 ON Table_1.acctnum = Table_2.acctnum AND Table_1.sub = Table_2.sub
where Table_1.sub>0
group by Table_1.acctnum
union
SELECT MIN(Table_1.acctnum) as acctnum , MIN(Table_1.sub) as sub,MIN( Table_1.fname) as fname, MIN(Table_1.lname) as name, MIN(Table_1.phone) as phone, MIN(Table_2.division) as division
FROM Table_1 INNER JOIN Table_2 ON Table_1.acctnum = Table_2.acctnum
where Table_1.sub=0
group by Table_1.acctnum
this is the result
12345 1 john doe xxxxxxxxxx EAST
12346 0 jane doe xxxxxxxxxx BOTTOM
12347 0 rob roy xxxxxxxxxx BALLOON
12348 0 paul smith xxxxxxxxxx NORTH
if you change min to max TOP will be insted of BOTTOM on the second row
It may also work for you:
SELECT t1.acctnum, t1.sub, t1.fname, t1.lname, t1.phone,
ISNULL(MAX(t2.division),MAX(t3.division)) as division
FROM table_1 t1
LEFT JOIN table_2 t2 ON (t2.acctnum = t1.acctnum AND t1.sub = t2.sub)
LEFT JOIN table_2 t3 ON (t3.acctnum = t1.acctnum)
GROUP BY t1.acctnum, t1.sub, t1.fname, t1.lname, t1.phone
This will give your desired result, exactly (for the shown data):
Updated to not assume there is always a sub==1 value:
SELECT
T1.acctnum,
T1.sub,
T1.fname,
T1.lname,
T1.phone,
T2.division
FROM
TABLE_1 T1
LEFT JOIN
TABLE_2 T2 ON T1.acctnum = T2.acctnum
AND
T2.sub = (SELECT MIN(T3.sub) FROM TABLE_2 T3 WHERE T1.acctnum = T3.acctnum)
ORDER BY
T1.lname,
T1.fname,
T1.acctnum