SQL query - filter with cascading conditions - sql

I've two tables T1 and T2 with the following columns -
T1
Project_ID
Category
Column_X
Column_Y
Column_Z
T2
Proj_ID
Category
Parent_Project_ID
I want to write a query to get records from T1 with the following condition -
Get Projects with Category = "A" from T1
Get child projects of the above filtered projects
I'm not sure how to check the second condition only with the results coming out of first condition.
What is needed?
Projects from T1 where Category is A
Child projects of projects obtained from condition 1
Adding sample data and desired results as requested -

To get all records from second table then you can use the following query.
SELECT
t2.*
FROM T1 t1
RIGHT OUTER JOIN T2 t2 ON t1.Project_ID = t2.Project_ID
WHERE t1.Category = "A"

SELECT * FROM T2 WHERE T2.Proj_ID IN ( SELECT Project_ID FROM T1 WHERE Category = 'A' )
This should do the job needed.
SELECT * from T2 as d
WHERE EXISTS ( SELECT * from T1 as d1 where d1.Category = 'A' and d1.Project_ID = d.Proj_ID )
SELECT * from T1 as d1 right join T2 as d2 on d1.Project_ID = d2.Proj_ID
WHERE d1.CodTert = 500
I've made an update, these query give the same result, one uses the JOIN one doesn't.

I'm assuming that T2.Parent_Project_ID and T1.Project_ID are related. If so, you can use this:
Select T3.*
From T1
Join T2 On T2.Parent_Project_ID = T1.Project_ID
Join T1 T3 On T3.Project_ID = T2.Proj_ID
Where T1.Category = 'A'
This would get only child projects of projects that have a category of 'A'.

EDIT:
Based on the output format that has been added to the question, the following query, which uses a LEFT OUTER JOIN would render the exact result required:
SELECT
T2.PROJ_ID Project_ID,
T2.Category,
T1.Column_X,
T1.Column_Y,
T1.Column_Z,
T2.Parent_Project_ID
FROM T1 T1_PARENTS
INNER JOIN T2
ON T2.Parent_Project_ID = T1.Project_ID and T1.Category = 'A'
INNER JOIN T2 T2_CHILDREN
ON T2_CHILDREN.PROJ_ID = T2.Parent_Project_ID OR T2_CHILDREN.Parent_Project_ID = T2.Parent_Project_ID
LEFT OUTER JOIN T1
ON T2_CHILDREN.PROJ_ID = T1.Project_ID;

Related

How to join one table with two different tables with similar fields in BigQuery?

I have 3 tables in BigQuery.
I need to join first one (contains ids), to others (contains list of values for ids). I want to have sum of values by ids from two tables:
SELECT t0.id, sum(values) FROM t0
LEFT JOIN t1 ON t0.id = t1.id
LEFT JOIN t2 ON t0.id = t2.id
GROUP BY id
It does not work with an error Column name values is ambiguous
What is the best way to make it?
SELECT t0.id, sum(t1.values) + sum(t2.values) as sumOfValues FROM t0
LEFT JOIN t1 ON t0.id = t1.id
LEFT JOIN t2 ON t0.id = t2.id
GROUP BY id
I think below better reflect your original idea
#standardSQL
SELECT id, sum(u.values)
FROM t0
LEFT JOIN (
SELECT id, values FROM t1 UNION ALL
SELECT id, values FROM t2
) u
USING (id)
GROUP BY id

How to get first row value from third table while joining three tables

I'm new to mssql .Here am trying to get values from database by joining three tables .
Table 1:
Table 2 :
Here the image there is a possibility for a single user can have multiple image id form this I need to take any one of the image.
Table 3 :
Here am joining the Table 1 and Table 2 by using H_ID
and Table 2 and Table 3 by using IMG_ID.
What I want to do is Need to get all the colum values from Table 1 and Table 2 But the first URL from the Table 3.
In this case an employee has multiple images in the Table I need to take the 1 URL.
Result should be like this :
Query :
SELECT T1.H_ID AS 'ID',
T1.NAME,
T1.ROLE,
T2.SALARY,
T3.IMAGE
FROM TABLE1 T1
JOIN TABLE2 T2
ON T1.H_ID T2.H_ID
JOIN TABLE3 T3
ON T3.IMG_ID = T2.IMG_ID
WHERE T1.STATUS = 'ACTIVE'
Now this query returns 3 rows for the id H_ID = 1001 but It should be a single row.
Can anyone help me to fix this .
use row_number()
with cte as
(SELECT T1.H_ID AS 'ID',T1.NAME,T1.ROLE,T2.SALARY,T3.IMAGE
,row_number() over(partition by T2.img_id order by T3.id) rn
FROM TABLE1 T1
JOIN TABLE2 T2
ON T1.H_ID T2.H_ID
JOIN TABLE3 T3
ON T3.IMG_ID = T2.IMG_ID WHERE T1.STATUS = 'ACTIVE'
) select * from cte where rn=1
After you comments it seems you need subquery
select T1.*,T2.sal,a.url
FROM TABLE1 T1
JOIN TABLE2 T2
ON T1.H_ID T2.H_ID
left join ( select min(id),img_id,url from table3 group by img_id,url) a
on T2.IMG_ID= a.img_id
WHERE T1.STATUS = 'ACTIVE'
I think, You can simply use OUTER APPLY and TOP 1 for that
SELECT T1.H_ID AS 'ID',
T1.NAME,
T1.ROLE,
T2.SALARY,
T3.IMAGE
FROM TABLE1 T1
JOIN TABLE2 T2 ON T1.H_ID T2.H_ID
OUTER APPLY(SELECT TOP 1 T3.IMAGE
FROM TABLE3 T3 WHERE T3.IMG_ID = T2.IMG_ID
--ORDER BY <column_name> --to take top 1 value in specific order
) T3
WHERE T1.STATUS = 'ACTIVE'

Duplicate table name (csuser.t2) in the FROM clause in inner join

Below is the query which is throwing error : as Duplicate table name (csuser.t2) in the FROM clause in inner join
SELECT t1.rxno,
t1.txno,
t2.create_datetime FROM mrgrxtxt t1,rx t2
INNER JOIN (
SELECT rxno,
t1. MIN(txno) AS min_txno,
t2. MAX(create_datetime) AS latest_txno
FROM mrgrxtxt t1 , rx t2
GROUP BY 1
) t2 ON t1.rxno = t2.rxno WHERE t2.min_txno > 8
AND t2.create_datetime = t2.latest_txno;
Can anybody helpout here?? This is informix DB.
You have defined two aliases as t2 one for rx and another for the sub query. Try changing the second t2 to something else like t3.
SELECT t1.rxno,
t1.txno,
t2.create_datetime
FROM mrgrxtxt t1
JOIN rx t2 ON t1.rxno = t2.rxno
INNER JOIN(
SELECT rxno,
t1. MIN(txno) AS min_txno,
t2. MAX(create_datetime) AS latest_txno
FROM mrgrxtxt t1
JOIN rx t2 ON t1.rxno = t2.rxno
GROUP BY 1
) t3 ON t1.rxno = t3.rxno
WHERE t3.min_txno > 8 AND t2.create_datetime = t3.latest_txno;

SQL: Calculating the Max date across multiple tables

I am trying to find the max date across multiple columns (in multiple tables). I have an SQL query that I think is almost workable, but am having a hard time debugging it. The problem is that it never returns anything. Any ideas on what I'm doing incorrectly? I don't get any errors, just an empty row "maxdate."
Here's my query:
SELECT
(
SELECT MAX(dates) FROM
(
SELECT dates = t1.UpdateDate
UNION ALL
SELECT dates = t2.UpdateDate
UNION ALL
SELECT dates = t3.UpdateDate
UNION ALL
SELECT dates = t4.UpdateDate
) as dateAcrossColumns
) as maxdate
FROM table1 as t1
join table2 as t2 on t1.ID = t2.ID
join table3 as t3 on t1.ID = t3.ID
join table4 as t4 on t1.ID = t4.ID
join table5 as t5 on t1.Status = t5.Status
WHERE t1.id = #param and t5.status <> 3
First join you join to table 2 using table 1's ID and table 3's ID. I presume you mean table 1's ID and table 2's ID?
join table2 as t2 on t1.ID = t3.ID
Should be:
join table2 as t2 on t1.ID = t2.ID
Now that this has been changed;
I tried your query and it works fine, are you sure that your joins are bringing back any rows? To test it replace your SELECT statement with SELECT *, if you get no rows back then they are being filtered out somewhere in your joins / WHERE.
If it's possible for any of the tables to not have any rows for the given #param, the (inner) joins will filter out all of the other tables.
Try unioning the dates and get the max of the unions
WITH allDates AS (
SELECT UpdateDate
FROM Table1
WHERE ID = #param
UNION
SELECT UpdateDate
FROM Table2
WHERE ID = #param
UNION
SELECT UpdateDate
FROM Table3
WHERE ID = #param
UNION
SELECT UpdateDate
FROM Table4
WHERE ID = #param
UNION
SELECT t5.UpdateDate
FROM Table5 AS t5
JOIN Table1 AS t1
ON t5.Status = t1.Status
WHERE t1.ID = #param
)
SELECT MAX( UpdateDate ) AS MaxDate
FROM allDates
Cant think of a simpler way of doing this :)
SELECT MAX(Dates) AS RequiredDate
FROM (
SELECT t1.UpdateDate AS DateOne
,t2.UpdateDate AS DateTwo
,t3.UpdateDate AS DateThree
,t4.UpdateDate AS DateFour
FROM table1 as t1
join table2 as t2 on t1.ID = t2.ID
join table3 as t3 on t1.ID = t3.ID
join table4 as t4 on t1.ID = t4.ID
join table5 as t5 on t1.[Status] = t5.[Status]
WHERE t1.id = #param and t5.[Status] <> 3
)t
UNPIVOT (Dates FOR DateCols
IN (DateOne, DateTwo,DateThree,DateFour))up
I was trying to solve a similar problem to find the last modified date across a set of joined tables in MySQL. The following worked for me using a combination of GREATEST and MAX:
SELECT GREATEST(MAX(t1.modified), MAX(t2.modified), MAX(t3.modified),
MAX(t4.modified)) AS lastmodified
FROM `table1` AS t1
LEFT JOIN `table2` AS t2 ON t1.id = t2.t1_id
LEFT JOIN `table3` AS t3 ON t2.id = t3.t2_id
LEFT JOIN `table4` AS t4 ON t3.id = t4.t3_id
WHERE t1.id = #param

SQL Joining three tables and using LEFT OUTER JOIN

I have three tables and two seperate SQL queries which are working correctly and I am having correct results.
If I try to join these three tables I am having null as result.
First query:
select T1.ID,T3.COMPANY
from T1,T3
where (T1.status!='CLOSED') and (T1.PRIORITY)>5 and T1.CLASSID=T3.CLASSID
Second query:
SELECT T1.ID, T2.DESCRIPTION
FROM T1
LEFT OUTER JOIN T2
ON T1.ID=T2.KEY
WHERE T1.status!='CLOSED'
AND (T2.CREATEDATE= (SELECT MAX(CREATEDATE)
FROM T2
WHERE T2.KEY=T1.ID))
I tried to join them but as result I am having null:
select T1.ID,T3.COMPANY,T2.DESCRIPTION
from T1
INNER JOIN T3 ON T1.CLASSID=T3.CLASSID
LEFT OUTER JOIN T2
ON T1.ID=T2.KEY
where (T1.status!='CLOSED') AND (T1.PRIORITY)>5
AND (T2.CREATEDATE= (SELECT MAX(CREATEDATE)
FROM T2
WHERE T2.KEY=T1.ID))
like it does not recognized last part for taking MAX value from T2 table.
What am I doing wrong? Thanks for help
Firstly, use an alias for the subquery on table T2.
T2.CREATEDATE =
(SELECT MAX(T2Alias.CREATEDATE)
FROM T2 AS T2Alias
WHERE T2Alias.KEY = T1.ID)
Secondly, consider moving this condition into the ON clause of the LEFT JOIN to table T2.
The first thing that jumps out at me is the new dependency on both T1.Priority > 5 and T2.CreateDate value being equal to the result of the inline query:
( AND (T1.PRIORITY) > 5
AND (T2.CREATEDATE =
(SELECT MAX(CREATEDATE) FROM T2 WHERE T2.KEY = T1.ID) )
Without the data it's difficult to check however this may be the issue