Left Joining on Multiple Tables with Timestamps - sql

Ok SQL and Oracle gurus I have a somewhat complicated query that I'm trying to build.
Here is my current query:
select distinct person_info.person_name
table2.value,
table3.value,
table4.value,
table5.value
from person_info
left join table2 on table2.person_name=person_info.person_name
left join table3 on table3.person_name=person_info.person_name
left join table4 on table4.person_name=person_info.person_name
left join table5 on table5.person_name=person_info.person_name;
The primary key for every table is both the person_name and a timestamp. Now my problem is that if multiple instances of the same person_name exist in a table then I only want to left join on the most recent one. Does anyone know how to add this behavior to this query? I am using Oracle.
Thanks!

Try:
select distinct person_info.person_name
t2.value,
t3.value,
t4.value,
t5.value
from person_info
left join (select t.*, row_number() over (partition by person_name order by timestamp_column desc) rowno from table2 t) t2
on t2.person_name=person_info.person_name and t2.rowno=1
left join (select t.*, row_number() over (partition by person_name order by timestamp_column desc) rowno from table3 t) t3
on t3.person_name=person_info.person_name and t3.rowno=1
left join (select t.*, row_number() over (partition by person_name order by timestamp_column desc) rowno from table4 t) t4
on t4.person_name=person_info.person_name and t4.rowno=1
left join (select t.*, row_number() over (partition by person_name order by timestamp_column desc) rowno from table5 t) t5
on t5.person_name=person_info.person_name and t5.rowno=1;

Related

How to implement a LEFT OUTER JOIN CLAUSE after WITH AS?

Currently trying to figure out how to implement a SQL LEFT OUTER JOIN while using the SQL WITH AS clause. My code breaks down into 3 SELECT statements while using the same table, then using LEFT OUTER JOIN to merge another table on the id.
I need 3 SELECT statements before joining because I need a SELECT statement to grab the needed columns, ROW RANK the time, and set WHERE clause for the ROW RANK.
SELECT *
(
WITH employee AS
(
SELECT id, name, department, code, time, reporttime, scheduled_time
FROM table1 AS a
WHERE department = "END"
),
employe_v2 as
(
SELECT address
,ROW_NUMBER() OVER (PARTITION BY id ORDER BY time desc, reporttime desc, scheduled_time desc) AS row_rank
FROM table1 AS b
)
SELECT *
FROM employee, employee_v2
WHERE row_rank = 1
) t1
LEFT OUTER JOIN
(
SELECT b.id, b.new_code, b.date
FROM table2 AS b
WHERE b.newcode != "A"
) t2
ON t1.id = t2.id
Group BY t1.id, t1.name, t1.department, t1.code, t1.time, t1.reporttime,
t1.scheduled_time, t1.row_rank, t2.id, t2.new_code, t2.date
How I could fix my code?
not sure if group by is needed, i see no aggregation whatsover
but if it's something you need , you can add at the end of final select and ofcourse you have to take care of columns/aggregation in select
nevertheless you can simplify your query as below :
with employee as (
select * from (
select id, name, department, code, time, reporttime, scheduled_time, address
,row_number() over (partition by id order by time desc, reporttime desc, scheduled_time desc) AS row_rank
from table1
) t where row_rank =1
)
select t1.*, b.id, b.new_code, b.date
from employee t1
left join table2 as t2
on t1.id = t2.id
where t2.newcode != "A"

Oracle-Join with same table multiple times with different where condition

Here is my case,
SELECT
A.TAB1_COL1,B.TAB2_COL4,C.TAB2_COL4
FROM TABLE1 A,
LEFT OUTER JOIN
(SELECT * FROM
(SELECT TAB2_COL1, TAB2_COL2, TAB2_COL4, ROW_NUMBER() OVER (PARTITION BY TAB2_COL1,TAB2_COL2 ORDER BY TAB2_COL3 DESC ) AS ROW_NUM
FROM TABLE2
WHERE TAB2_COL2=2
) WHERE ROW_NUM=1
) B ON A.TAB1_COL1=B.TAB2_COL1
LEFT OUTER JOIN
(SELECT * FROM
(SELECT TAB2_COL1, TAB2_COL2, TAB2_COL4, ROW_NUMBER() OVER (PARTITION BY TAB2_COL1,TAB2_COL2 ORDER BY TAB2_COL3 DESC ) AS ROW_NUM
FROM TABLE2 WHERE TAB2_COL2=5
) WHERE ROW_NUM=1
) C ON A.TAB1_COL1=C.TAB2_COL1 AND A.TAB1_COL2=C.TAB2.COL5
LEFT OUTER JOIN
(SELECT * FROM
(SELECT TAB2_COL1, TAB2_COL2, TAB2_COL4, ROW_NUMBER() OVER (PARTITION BY TAB2_COL1,TAB2_COL2 ORDER BY TAB2_COL3 DESC ) AS ROW_NUM
FROM TABLE2 WHERE TAB2_COL2=8
) WHERE ROW_NUM=1
) D ON A.TAB1_COL1=D.TAB2_COL1
This code will work.But, I'm left joining with same table multiple times. In my case, it was around 25 times. Reference table has around 200 million records. Partition to remove dups is taking much time.
Any other effective way of writing to make it process faster. Kindly help.
Thanks
If I understand correctly, you can use conditional aggregation:
select t1.tab1_col1,
max(case when tab2_col2 = 2 then tab2_col4 end),
max(case when tab2_col2 = 5 then tab2_col4 end),
max(case when tab2_col2 = 8 then tab2_col4 end)
from table1 t1 left join
(select t2.*,
row_number() over (partition by tab2_col1, tab2_col2 order by tab2_col3 desc) as seqnum
from table2 t2
) t2
on t1.tab1_col1 = t2.tab2_col1
group by t1.tab1_col1;

tsql: alternative to select subquery in join

this is my table layout simplified:
table1: pID (pkey), data
table2: rowID (pkey), pID (fkey), data, date
I want to select some rows from table1 joining one row from table2 per pID for the most recent date for that pID.
I currently do this with the following query:
SELECT * FROM table1 as a
LEFT JOIN table2 AS b ON b.rowID = (SELECT TOP(1) rowID FROM table2 WHERE pID = a.pID ORDER BY date DESC)
This way of working is slow, probabaly because it has to do a subquery on each row of table 1. Is there a way to improve performance on this or do it another way?
You can try something on these lines, use the subquery to get the latest based on the date field (grouping by the pID), then join that with the first table, this way the subquery would not have not have to be executed for each row of Table1 and will result in better performance:
Select *
FROM Table1 a
INNER JOIN
(
SELECT pID, Max(Date) FROM Table2
GROUP BY pID
) b
ON a.pID = b.pID
I have provided the sample SQL for one column using the group by, in case you need additional columns, add them to the GROUP BY clause. Hope this helps.
use the below code, and note that i added the order by Date desc to get the most resent data
select *
from table1 a
inner join table2 b on a.pID=b.pID
where b.rowID in(select top(1) from table2 t where t.pID=a.pID order by Date desc)
I am using the code below in a similar scenaro (I transcripted it to your example)
SELECT b.*
FROM table1 AS a
left outer join (
SELECT a.*
FROM table2 a
inner join (
SELECT a.pID, max(date) as date
FROM table2
WHERE date <= <max_date>
group by pID
) b ON a.pID = b.pID AND a.date = b.date
) b ON a.pID = b.pID
) b on a.pID = b.pID
The only problem with this aproach is that you have to make sure the date's don't reapet for the pID's
You can do this with the row_number() function and a subquery:
SELECT t1.*
FROM table1 t1 LEFT JOIN
(select t2.*, row_number() over (partition by pId order by rowId desc) as seqnum
from table2 t2
) t2
on t1.pId = t2.pId and t2.seqnum = 1;
Use the ROW_NUMBER() function to get a column saying which id of each row in table 2 is the first (As partitioned by the pID, and ordered by the rowDate descending)
Example:
WITH cte AS
(
SELECT
rowID AS t2RowId,
ROW_NUMBER OVER (PARTITION BY pID ORDER BY rowDate DESC) AS rowNum
FROM table2 t2
) -- gets the t2RowIds + a column which says which is the latest for each pID
SELECT t1.*, t2.*
FROM table1 t1
LEFT JOIN
(
table2 t2
JOIN cte ON t2.rowID = cte.t2RowId AND cte.rowNum = 1
) ON t1.pID = t2.pID
This is guaranteed to only return 1 item from table2 per pID, even if multiple items have the same date. You should of course ensure that the date column is indexed in table 2 for quick performance (ideally an index that also covers the PrimaryID of table2)

How to Select master table data and select referance table top one data sql query

i need an sql query which should return the master table entry and its child table entry (the latest one entry only). I used inner join for this. But i its not working fine.
Can anyone give a give me a proper query for this
Thanks in advance
In SQLServer2005+ use option with OUTER APPLY operator
SELECT *
FROM master t1 OUTER APPLY (
SELECT TOP 1 t2.Col1, t2.Col2 ...
FROM child t2
WHERE t1.Id = t2.Id
ORDER BY t2.CreatedDate DESC
) o
OR option with CTE and ROW_NUMBER() ranking function
;WITH cte AS
(
SELECT *,
ROW_NUMBER() OVER(PARTITION BY t1.Id ORDER BY t2.CreatedDate DESC) AS rn
FROM master t1 JOIN child t2 ON t1.Id = t2.Id
)
SELECT *
FROM cte
WHERE rn = 1
Try this,
SELECT ID, DATE
(
SELECT M.ID, C.DATE, ROW_NUMBER() OVER(PARTITION BY M.ID ORDER BY C.DATE DESC) RN
FROM MASTER M
JOIN CHILD C
ON C.ID = M.ID
) A
WHERE RN = 1

join columns on the same table without declaring a table

I have a complex query to populate data and after than
i have to join the data in the table to get the right result.
How to eliminate the join such that i do not have to define the table two times.
The join query being -
select t1.acc_no, t1.group_id, t1.remdt from #tbl t1
inner join (
select group_id, MAX(row_num) as max_row from #tbl group by group_id) t2
on t1.group_id= t2.group_id and t1.row_num=t2.max_row
now in the above query i have to decalre #tbl temp table.
How to get the same result such that i dont have to do using the join and do not have to write the same query twice.
My #tbl is populated using the sql -
select ReminderDt as 'rem dt', m.Group_Id, m.AccountNumber,
row_number() over (partition by group_id order by reminderdt asc) as seqnum
from ACE_AccsLevelTran t join ACE_AccsLevelMaster m on t.MasterAccNumber=m.AccountNumber where m.AssignedUser=7
Thanks
You can do this with a window function, row_number():
select t.acc_no, t.group_id, t.remdt
from (select t.*, ROW_NUMBER() over (partition by group_id order by row_num desc) as seqnum
from #tbl t
) t
where seqnum = 1;