Return two relationship in one resultset - sql

Below are the oversimplified inspired from my production schema.
Thus, I want to return all these information in one result set.
My desired result set
I have tried this query but it return wrong result.
SELECT u.*
,f.*
,uv.*
,v.*
FROM User u
LEFT JOIN UserFarm uf ON uf.UserID = u.ID
LEFT JOIN Farm f ON f.ID = uf.FarmID
LEFT JOIN FarmVehicle fv ON f.ID = fv.FarmID
LEFT JOIN UserVehicle uv ON u.ID = uv.UserID
LEFT JOIN Vehicle v ON fv.VehicleID = v.ID
WHERE u.ID = 1
Edit: This is the result from above query.
Could anyone advise me on this, I really need to return in the desired result.

You could build a query to return the data you want in the first row, and null in the columns you don't want for that row. Then create another query for the second row and use union all to combine the data together:
declare #UserVehicle table (UserID int, VehicleID int, IsService bit)
declare #User table (ID int, Name varchar(10))
declare #UserFarm table (UserID int, FarmID int)
declare #Farm table (ID int, Name varchar(10))
declare #FarmVehicle table (FarmID int, VehicleID int)
declare #Vehicle table (ID int, [Type] varchar(10), Name varchar(10))
insert into #UserVehicle values (1, 2, 1)
insert into #User values (1, 'Sam')
insert into #UserFarm values (1, 1)
insert into #Farm values (1, 'Flora')
insert into #FarmVehicle values (1, 1)
insert into #Vehicle values (1, 'Larry', 'Scania'), (2, 'Unknown', 'Civic')
select [User.ID] = u.ID
,[User.Name] = u.Name
,[Farm.ID] = f.ID
,[Farm.Name] = f.Name
,[UserVehicle.UserID] = null
,[UserVehicle.VehicleID] = null
,[UserVehicle.IsService] = null
,[Vehicle.ID] = v.ID
,[Vehicle.Name] = v.Name
from #User u
left join #UserFarm uf on u.ID = uf.UserID
left join #Farm f on uf.FarmID = f.ID
left join #FarmVehicle fv on f.ID = fv.VehicleID
left join #Vehicle v on fv.VehicleID = v.ID
union all
select [User.ID] = u.ID
,[User.Name] = u.Name
,[Farm.ID] = null
,[Farm.Name] = null
,[UserVehicle.UserID] = uv.UserID
,[UserVehicle.VehicleID] = uv.VehicleID
,[UserVehicle.IsService] = case when uv.IsService = 0 then 'No' else 'Yes' end
,[Vehicle.ID] = v.ID
,[Vehicle.Name] = v.Name
from #User u
left join #UserFarm uf on u.ID = uf.UserID
left join #UserVehicle uv on u.ID = uv.UserID
left join #Vehicle v on uv.VehicleID = v.ID
This query returns the following dataset:
User.ID User.Name Farm.ID Farm.Name UserVehicle.UserID UserVehicle.VehicleID UserVehicle.IsService Vehicle.ID Vehicle.Name
----------- ---------- ----------- ---------- ------------------ --------------------- --------------------- ----------- ------------
1 Sam 1 Flora NULL NULL NULL 1 Scania
1 Sam NULL NULL 1 2 Yes 2 Civic
If you do not want to see users who are not assigned to vehicles or farms, then change all left join to inner join.

Try with following query
SELECT U.*,T.* FROM (
SELECT F.FARMID,F.NAME AS NAM
,UV.*
,V.*
FROM VEHICLE V
LEFT JOIN FARMVEHICLE FV ON FV.VEHICLEID = V.ID
LEFT JOIN USERVEHICLE UV ON UV.VEHICLEID = V.ID
LEFT JOIN FARM F ON F.FARMID = FV.FARMID
LEFT JOIN USERFARM UF ON UF.FARMID = F.FARMID)T, USER U
Let me know if any issue in query.

You want to show a user's farms and vehicles. However farms and vehicles can be related, and in that case you want to show them together in a row rather than in separated rows.
Example: User1 is related to Farm1, Farm2, and Farm3 and to Vehicle1, Vehicle2, and Vehicle3. Moreover, Farm1 is related to Vehicle1 and Vehicle2 and Farm2 is also related to Vehicle1.
Then you want:
user | farm | vehicle
------+-------+---------
User1 | Farm1 | Vehicle1
User1 | Farm1 | Vehicle2
User1 | Farm2 | Vehicle1
User1 | Farm3 | -
User1 | - | Vehicle3
So the second and third columns show the relations of farms with vehicles. You get these with a full outer join. The join's ON clause is a bit tricky. You want the userid to match and the combination of farmid and vehicleid to be found in the bridge table farmvehicle. Here is one way to do this:
with rel as
(
select coalesce(uf.userid, uv.userid) as userid, uf.farmid, uv.vehicleid
from userfarm uf
full outer join uservehicle uv
on uf.userid = uv.userid
and exists (select * from farmvehicle fv where fv.farmid = uf.farmid
and fv.vehicleid = uv.vehicleid)
)
select u.name as user_name, f.name as farm_name, v.name as vehicle_name
from usr u
left join rel on u.id = rel.userid
left join farm f on f.id = rel.farmid
left join vehicle v on v.id = rel.vehicleid
order by user_name, farm_name, vehicle_name;
Rextester demo: http://rextester.com/DNKSU25931

Related

SQL Server inner join query from many to many relationship tables

I am new to SQL programming and I am having the following problem.
I have 3 tables :
tblMaschine (id PK, type as char(5))
tblUse (id PK, typeOfUse varchar(255))
tblmaschineUse (mid, uid both PK and each as FK to the above tables)
This is a many to many relationship. I have inserted this data in the tables:
tblmaschine
id|type
--+-----
1 |M1
2 |M2
3 |M3
tbluse
id|typeOfUse
--+---------
1 |U1
2 |U2
and
tblmaschineUse
id|type
--+-----
1 |1
1 |2
2 |1
3 |2
I want to query to find the maschine type from tblmaschine which has the both types of use in table maschineUse.
I am using this query but it returns nothing:
select m.type
from tblmaschine as m
inner join tblmaschineUse as mu on m.id = mu.mid
inner join use as u on u.id = mu.uid
where u.typeOfUse = 'U1' and u.typeOfUse = 'U2';
What am I doing wrong?
An option uses aggregation:
select m.id, m.type
from tblmaschine m
inner join tblmaschineUse mu on mu.id = m.id
where mu.type in (1, 2)
group by m.id, m.type
having count(*) = 2
This assumes no duplicates (id, type) in tblmaschineUse (otherwise, you need having count(distinct type) = 2.
If you want to filter on the name of the type, you need another join:
select m.id, m.type
from tblmaschine m
inner join tblmaschineUse mu on mu.id = m.id
inner join tbluse u on u.id = mu.type
where u.typeOfUse in ('U1', 'U2')
having count(*) = 2
You could also use two exists subqueries:
select m.*
from tblmaschine m
where
exists(select 1 from tblmaschineUse mu inner join tbluse u on u.id = mu.type where u.typeOfUse = 'U1' where mu.id = m.id)
and exists (select 1 from tblmaschineUse mu inner join tbluse u on u.id = mu.type where u.typeOfUse = 'U2' where mu.id = m.id)

MS-SQL 2008 issues with multiple tables query

I need help with writing a SQL query. My tables are:
Contribution:
contribution_id | amount | person_id | currency_type
Person
Person_id | firstname | lastname
related related_id | person_id | related_personID
Currency Type CurrencyTypeID | CurrencyName
There are other tables and fields, but these are the ones I need.
Here is the problem I am having..
When a person contributes the first and last name is easy, but when a Brokerage firm contributes, I need to include the real person first name and last name (not the Brokerage Account).
The Brokerage is on the same table as the person.
So far, i have if the contribution.currencyType = '12492' then i need to get the information from related table to find the real person_id.
What I do get when I run the code below is all the data, except when the currencytype = 12492 then I get null for first and last name.
Here is my code so far:
`
declare #fund int = 165
declare #payment_luid int = 58
DECLARE #report_information TABLE(
ContributionID varchar(20),
ContributionDate date,
firstname varchar(50),
lastname varchar(50),
memberID varchar(20),
Pledge money,
cash money,
non_cash money,
fund_name VARCHAR(50))
INSERT INTO #report_information
SELECT c.contribution_id,
c.contribution_date,
case when c.currency_type = '12492' then t3.first_name else t1.first_name end,
case when c.currency_type = '12492' then t3.last_name else t1.last_name end,
case when c.currency_type = '12492' THEN t3.person_id else c.person_id end as MemberID,
case when c.currency_type = '12492' then (select amount From ctrb_pledge where ctrb_pledge.person_id = t3.person_id and fund_id = #fund) else (select amount from ctrb_pledge where ctrb_pledge.person_id = c.person_id and fund_id =#fund) END,
CASE WHEN C.currency_type_luid NOT IN (SELECT lookup_id FROM core_lookup WHERE lookup_type_id=#payment_luid AND lookup_qualifier2 ='1') THEN CCF.amount ELSE 0 END,
CASE WHEN CCF.non_cash = 1 OR C.currency_type IN (SELECT lookup_id FROM core_lookup WHERE lookup_type_id=#payment_luid AND lookup_qualifier2 ='1') THEN CCF.amount ELSE 0 END,
f.fund_name
FROM contribution as c
left join core_person as t1
on t1.person_id = c.person_id
left join relationship as t2
on t2.person_id = c.person_id
left join person as t3
on related_person_id = c.person_id
JOIN ctrb_contribution_fund CCF ON CCF.contribution_id=C.contribution_id
JOIN ctrb_fund F ON F.fund_id = CCF.fund_id
where f.fund_id = #fund
order by contribution_id
SELECT lastname
,firstname
,memberID
,coalesce(SUM(pledge),0) as Pledge
,SUM(cash) AS cash_gifts
,SUM(non_cash) AS non_cash_gifts
,SUM(cash + non_cash) as TotalGiving
,coalesce(SUM(pledge)-(SUM(cash)+SUM(non_cash)),0) as Balance
,fund_name
FROM #report_information
GROUP BY memberid, lastname, firstname, fund_name
ORDER BY lastname asc
`
I figured this problem out. By changing the join statements to FULL JOIN OUTER my missing records appeared.
join core_person as cp
on cp.person_id = c.person_id
full outer join core_relationship as rel
on rel.person_id = c.person_id
full outer join core_person as newCp
on rel.related_person_id = newcp.person_id
I did change my table to something I can remember. t1 = cp,t2 = rel,t3 = newcp.

SQL Filtering rows with no duplicate value

Hi so I'm new to SQL and I'm trying to find a way in which I can obtain only the rows that have values that are not duplicate to each other in a specific column of table.
For example the Table below is called T1 and contains:
ID|Branch ID
1 444
2 333
3 444
4 111
5 555
6 333
The result I want will be
ID|Branch ID
4 111
5 555
So only showing non duplicate rows
Edit: I want to apply this to a large relational code. Here is a snippet of where I want it to be added
FROM dbo.LogicalLine
INNER JOIN dbo.Page ON dbo.LogicalLine.page_id = dbo.Page.id
INNER JOIN dbo.Branch ON dbo.LogicalLine.branch_id = dbo.Branch.id
The table LogicalLine will have a column called branch_id containing duplicate id values. I wish to filter those out showing only the non-duplicate branch_id like above example then INNER JOIN the Branch table into the LogicalLine which I have done.
Added -Full Code here:
SELECT
(SELECT name
FROM ParentDevice
WHERE (Dev1.type NOT LIKE '%cable%') AND (id = Dev1.parent_device_id))T1_DeviceID,
(SELECT name
FROM Symbol
WHERE (id = CP1.symbol_id) AND (type NOT LIKE '%cable%'))T1_DeviceName,
(SELECT name
FROM Location
WHERE (id = Page.location_id))T1_Location,
(SELECT name
FROM Installation
WHERE (id = Page.installation_id))T1_Installation,
(SELECT name
FROM ParentDevice
WHERE (Dev2.type NOT LIKE '%cable%') AND (id = Dev2.parent_device_id))T2_DeviceID,
(SELECT name
FROM Symbol
WHERE ( id = CP2.symbol_id) AND (type NOT LIKE '%cable%'))T2_DeviceName,
(SELECT name
FROM Location
WHERE (id = PD2.location_id))T2_Location,
(SELECT name
FROM Installation
WHERE (id = Page.installation_id))T2_Installation,
(SELECT devicefamily
FROM Device
WHERE (type LIKE '%cable%') AND (id = SymCable.device_id))CablePartNumber,
(SELECT name
FROM ParentDevice
WHERE (id = DevCable.parent_device_id) AND (DevCable.type LIKE '%cable%'))CableTag
FROM dbo.LogicalLine
INNER JOIN dbo.Page ON dbo.LogicalLine.page_id = dbo.Page.id
INNER JOIN dbo.Branch ON dbo.LogicalLine.branch_id = dbo.Branch.id
LEFT OUTER JOIN dbo.Symbol AS SymCable ON dbo.LogicalLine.cable_id = SymCable.id
LEFT OUTER JOIN dbo.Device AS DevCable ON SymCable.device_id = DevCable.id
LEFT OUTER JOIN dbo.ParentDevice AS ParentCable ON DevCable.parent_device_id = ParentCable.id
INNER JOIN dbo.SymbolCP AS CP1 ON dbo.Branch.cp1_id = CP1.id
INNER JOIN dbo.SymbolCP AS CP2 ON dbo.Branch.cp2_id = CP2.id
INNER JOIN dbo.Symbol AS S1 ON CP1.symbol_id = S1.id
INNER JOIN dbo.Symbol AS S2 ON CP2.symbol_id = S2.id
INNER JOIN dbo.Device AS Dev1 ON S1.device_id = Dev1.id
INNER JOIN dbo.Device AS Dev2 ON S2.device_id = Dev2.id
INNER JOIN dbo.ParentDevice AS PD1 ON Dev1.parent_device_id = PD1.id
INNER JOIN dbo.ParentDevice AS PD2 ON Dev2.parent_device_id = PD2.id
INNER JOIN dbo.Location AS L1 ON PD1.location_id = L1.id
INNER JOIN dbo.Location AS L2 ON PD2.location_id = L2.id
INNER JOIN dbo.Installation AS I1 ON L1.installation_id = I1.id
INNER JOIN dbo.Installation AS I2 ON L2.installation_id = I2.id
WHERE
(PD1.project_id = #Projectid) AND (dbo.LogicalLine.drawingmode LIKE '%Single Line%');
Select Id, BranchId from table t
Where not exists
(Select * from table
where id != t.Id
and BranchId = t.BranchId)
or
Select Id, BranchId
From table
Group By BranchId
Having count(*) == 1
EDIT: to modify as requested, simply add to your complete SQL query a Where clause:
Select l.Id BranchId, [plus whatever else you have in your select clause]
FROM LogicalLine l
join Page p ON p.id = l.page_Id
join Branch b ON b.Id = l.branch_id
Group By l.branch_id, [Plus whatever else you have in Select clause]
Having count(*) == 1
or
Select l.Id BranchId, [plus whatever else you have in your select clause]
FROM LogicalLine l
join Page p on p.id = l.page_Id
join Branch b on b.Id = l.branch_id
Where not exists
(Select * from LogicalLine
where id != l.Id
and branch_id = l.branch_id)

Joining Two Temp Tables

I would like to join two temp tables into one big temp table. I want all of the records from my first temp table and want the records from my second temp table ONLY if the ProductID doesn't exist in my first temp table.
First temp table:
--define temporary table
declare #tmp table (
ManagerID int null,
ManagerName varchar(250),
ProductID int null,
ProductName varchar(250),
RFIFixedIncomeAttributionID int null,
Value decimal(8,4) null,
Name varchar(250),
Sector varchar(250)
)
--populate temp table
insert into #tmp
select
m.ManagerID, m.ManagerName, p.ID as 'ProductID', p.ProductName, sa.RFIFixedIncomeAttributionID, sa.Value, sc.Name,
case when gm.GeographicMandateID = 2 and s1.SubType1ID = 10 and s2.SubType2ID = 39 then 'Core'
when gm.GeographicMandateID = 2 and s1.SubType1ID = 10 and s2.SubType2ID = 38 then 'Intermediate'
end as 'Sector'
from Products p
join Managers m on m.ManagerID = p.ManagerID
left join RFIFixedIncomeAttribution fia on fia.ParentID = p.ID and fia.ParentTypeID = 26
left join RFIFixedIncomeSectorAllocation sa on sa.RFIFixedIncomeAttributionID = fia.ID
and sa.RFIFixedIncomeDataTypeID = 1
join RFIFixedIncomeSectorCategories sc on sc.ID = sa.RFIFixedIncomeSectorCategoryID
join SubType1 s1 on s1.SubType1ID = p.SubType1ID
join SubType2 s2 on s2.SubType2ID = p.SubType2ID
join GeographicMandates gm on gm.GeographicMandateID = p.GeographicMandateID
where p.prodclasscategoryid = 4
and fia.year = 2014
and fia.quarter = 6/3
and p.Rank = 1
order by m.ManagerName, p.ProductName
--get filtered dataset
select * from #tmp
where
Sector in ('Core')
Second temp table:
--define temporary table
declare #tmp2 table (
ManagerID int null,
ManagerName varchar(250),
ProductID int null,
ProductName varchar(250),
RFIFixedIncomeAttributionID int null,
Value decimal(8,4) null,
Name varchar(250),
Sector varchar(250)
)
--populate temp table
insert into #tmp2
select
m.ManagerID, m.ManagerName, p.ID as 'ProductID', p.ProductName, sa.RFIFixedIncomeAttributionID, sa.Value, sc.Name,
case when gm.GeographicMandateID = 2 and s1.SubType1ID = 10 and s2.SubType2ID = 39 then 'Core'
when gm.GeographicMandateID = 2 and s1.SubType1ID = 10 and s2.SubType2ID = 38 then 'Intermediate'
end as 'Sector'
from Products p
join Managers m on m.ManagerID = p.ManagerID
join Vehicles v on v.ProductID = p.ID
join ManagerAccounts ma on ma.VehicleID = v.ID
join Accounts a on a.MgrAccountID = ma.MgrAccountID
left join RFIFixedIncomeAttribution fia on fia.ParentID = a.AccountID and fia.ParentTypeID = 6
left join RFIFixedIncomeSectorAllocation sa on sa.RFIFixedIncomeAttributionID = fia.ID
and sa.RFIFixedIncomeDataTypeID = 1
join RFIFixedIncomeSectorCategories sc on sc.ID = sa.RFIFixedIncomeSectorCategoryID
join SubType1 s1 on s1.SubType1ID = p.SubType1ID
join SubType2 s2 on s2.SubType2ID = p.SubType2ID
join GeographicMandates gm on gm.GeographicMandateID = p.GeographicMandateID
where p.prodclasscategoryid = 4
and fia.year = 2014
and fia.quarter = 6/3
and p.Rank = 1
order by m.ManagerName, p.ProductName
--get filtered dataset
select * from #tmp2
where
Sector in ('Core')
Few points that have already brought up
Union is the term you want, join is something quite different.
You are not working with temp tables, you are working with table variables. Not quite the same thing
mysql and mssql are not the same thing, tag your questions as one or the other, not both.
select * from #tmp
union all
select * from #tmp2 where productID not in (select productID from #tmp)
Not sure if I'd rely on this query in MySQL as it'll struggle with the not in clause...you can use the join syntax in Jasmine's answer for the second half of the union clause.
This is a case of "find all rows with NO MATCH in the other table" and we have a pattern for that. First, swap your tables - the table where you expect to be missing rows will be the second or RIGHT table, the other is the LEFT table.
select <columns>
from table1
LEFT OUTER JOIN table1.ID = table2.ID
where table2.ID IS NULL
OR... don't swap the tables and use RIGHT OUTER JOIN - but that's non-standard.
In your code, there's a problem...
and fia.quarter = 6/3
is equivalent to:
and fia.quarter = 2
I think you need some quotation marks there.

Case or If, What to choose in SQL

How can i manage this query. I want to have only one person in the query. If there is an id in empId column, then the name of him. Otherwise the name of the boss.
Product empId teamId
----------------------
A 1 3
B 2 4
C 3
D 2 3
E 4
User Table
Id Name
-----------
1 Jim
2 Carrey
3 Bill
4 Clinton
Team Table
Team_Id BossId
-----------
3 3
4 4
The result should look like:
Product user.name
-----------------
A Jim
B Carrey
C Bill
D Carrey
E Clinton
Use CASE or the COALESCE() function:
SELECT
x.Product
, COALESCE(emp.Name, boss.Name) AS Name
FROM
TableX AS x
LEFT JOIN
User AS emp
ON emp.Id = x.empId
LEFT JOIN
User AS boss
ON boss.Id = x.bossId
Updated:
SELECT
x.Product
, COALESCE(emp.Name, boss.Name) AS Name
FROM
TableX AS x
LEFT JOIN
User AS emp
ON emp.Id = x.empId
LEFT JOIN
Team As t
JOIN
User AS boss
ON boss.Id = t.bossId
ON t.team_Id = x.teamId
Something like this:
SELECT
Table1.Product,
CASE
WHEN Table1.empId IS NULL
THEN Boss.name
ELSE Emp.name
END
FROM
Table1
LEFT JOIN [User] AS Emp
ON Emp.Id =Table1.empId
LEFT JOIN Team
ON Team.Team_Id =Table1.teamId
LEFT JOIN [User] AS Boss
ON Boss.Id=Team.BossId
SELECT Y.Product, U.Name
FROM YourTable AS Y
JOIN Users AS U ON Y.empId = U.Id
UNION
SELECT Y.Product, U.Name
FROM YourTable AS Y
JOIN Team AS T ON Y.teamId = T.Team_Id
JOIN Users AS U ON T.BossId = U.Id
WHERE Y.empId IS NULL;
-- SET search_path='tmp';
DROP TABLE tmp.products;
CREATE TABLE products
( product CHAR(1)
, emp_id INTEGER
, team_id INTEGER
);
INSERT INTO products(product,emp_id,team_id)
VALUES ('A',1,3), ('B',2,4), ('C',NULL,3), ('D',2,3), ('E',NULL,4);
DROP TABLE tmp.names;
CREATE TABLE names
(id INTEGER
, zname varchar
);
INSERT INTO names(id,zname)
VALUES ( 1, 'Jim') ,( 2, 'Carrey') ,( 3, 'Bill') ,( 4, 'Clinton') ;
DROP TABLE tmp.teams;
CREATE TABLE teams
( team_id INTEGER NOT NULL
, boss_id INTEGER NOT NULL
);
INSERT INTO teams(team_id,boss_id) VALUES ( 3,4) , (4,4);
WITH lutser(prod,id,team) AS
(
SELECT k1.product AS prod
, k1.emp_id AS id
, k1.team_id AS team
FROM tmp.products k1
UNION
SELECT k2.product AS prod
, t.boss_id AS id
, k2.team_id AS team
FROM tmp.products k2
JOIN tmp.teams t ON t.team_id = k2.team_id
WHERE k2.emp_id IS NULL
)
SELECT l.prod
, l.id
, l.team
, n.zname
FROM lutser l
JOIN names n ON n.id = l.id
;
extra bonus point for a recursive version of this CTE ...