Combining sql queries - sql

I am new to T SQL, I have two query's that I need to combine them according to common column value.
Both query are working fine individually.
First query is
SELECT t_senderTable.nameFull AS "senderName", t_recieverTable.recieverName AS "recieverName"
FROM ((dbo.t_senderTable AS t_senderTable
INNER JOIN t_senderTable AS t_senderTable ON (t_senderTable.Kd = mapTable.senderID))
INNER JOIN t_recieverTable AS t_recieverTabler ON (recieverTable.Id = mapTable.recieverID )
Second query is
SELECT t_license AS "License", t_coName AS "Company Name"
FROM (dbo.t_license AS t_license
INNER JOIN dbo. t_coName ON ( t_coName.id = t_license.senderID ))
WHERE
(
t_license.check < '2' )
Basically I need to combine the two query's, so that using senderID that is common between two query's I get output result of senderName, recieverName and coName
senderID is one to many relation.
Was getting idea from this post but cant get it to work Combining SQL Server Queries
Any ideas how to go about it? Thanks

You can use UNION(removes duplicate rows) or UNION ALL(returns all rows). For it to work, your columns need to match in both queries.

You could put the two queries as subqueries, include the senderId field in the select clause of both the subqueries and join on those values. I think what you are asking for is:
SELECT q1.senderName
, q1.recieverName
, q2."Company Name"
(
SELECT t_senderTable.nameFull AS "senderName", t_recieverTable.recieverName AS "recieverName"
, t_senderTable.Id
FROM ((dbo.t_senderTable AS t_senderTable
INNER JOIN t_senderTable AS t_senderTable ON (t_senderTable.Kd = mapTable.senderID))
INNER JOIN t_recieverTable AS t_recieverTabler ON (recieverTable.Id = mapTable.recieverID )
) q1
INNER JOIN (
SELECT t_license AS "License", t_coName AS "Company Name"
, t_license.senderID
FROM (dbo.t_license AS t_license
INNER JOIN dbo. t_coName ON ( t_coName.id = t_license.senderID ))
WHERE
(
t_license.check < '2' )
) q2
ON q1.Id = q2.senderId

Related

Merge A nested Query with another result in SQLite

I have two sets of queries:
SELECT
t.series_name,
ti.num_views_per_telecast
FROM
(
SELECT
ti.telecast_id,
ti.network_id,
count(*) as num_views_per_telecast
FROM
tunein AS ti
INNER JOIN affiliates AS a ON ti.network_id = a.network_id
WHERE
ti.dvr_time_shift = 'L+SD'
and a.network_name = 'ABC'
group by
ti.telecast_id,
ti.network_id
) ti
inner join telecast AS t On t.telecast_id = ti.telecast_id
ORDER BY
ti.num_views_per_telecast DESC
And
select
distinct *
from
telecast
where
episode_name = 'friday night dinner'
and series_name = 'A Million Little Things'
and date(program_start_local) = '2018-10-17'
I want to be able to combine the two so that I can get the num_views_per_telecast for the episodes in the bottom query. Not quite sure how I would inner join these though so I could keep the results from the first set of queries.
How the tables are connected are below:
How would I combine these???
At a guess:
SELECT
t.*,
ti.num_views_per_telecast
FROM
(
SELECT
ti.telecast_id,
ti.network_id,
count(*) as num_views_per_telecast
FROM
tunein AS ti
INNER JOIN
affiliates AS a
ON
ti.network_id = a.network_id
WHERE
ti.dvr_time_shift = 'L+SD' and
a.network_name = 'ABC'
group by
ti.telecast_id,
ti.network_id
)ti
inner join telecast AS t
On
t.telecast_id = ti.telecast_id
--from query2
where
t.episode_name = 'friday night dinner'
and t.series_name = 'A Million Little Things'
and t.date(program_start_local) = '2018-10-17'
ORDER BY ti.num_views_per_telecast DESC
For reasons given in the comment, the DISTINCT is redundant so you seem to want all rows from telecast that match some criteria. Given that your first query contains telecast but without any criteria and you only select one column from it, merging the two is a case of boosting the number of columns selected to (all from telecast) plus anything else, and adding the where clause from query 2 to restrict the rows in query 1

SQL left joins returning weird IDs

I am running this SQL query in a SQL Server database,
SELECT staff_list.id AS staff_id,
staff_list.status,
core_teams.workbase,
core_teams.service_user,
core_teams.staff_name,
core_teams.role,
service_users.id AS su_id
FROM staff_list
LEFT JOIN core_teams
ON staff_list.workbase = core_teams.workbase
LEFT JOIN service_users
ON service_users.name = core_teams.service_user
WHERE staff_list.status <> 'Left'
AND staff_list.status <> 'Name Changed';
The join and results are being returned, however the attribute staff_id is being repeated multiple times over many rows for users that have relevance to the staff_id. Am I doing something incorrectly?
You may be missing a link between staff_list and core_teams.
SELECT staff_list.id AS staff_id, staff_list.status,
core_teams.workbase, core_teams.service_user, core_teams.staff_name,
core_teams.role, service_users.id AS su_id
FROM staff_list
LEFT JOIN core_teams
ON staff_list.workbase = core_teams.workbase
--missing link
AND staff_list.name = core_teams.staff_name
LEFT JOIN service_users
ON service_users.name = core_teams.service_user
WHERE staff_list.status <> 'Left'
AND staff_list.status <> 'Name Changed';

SQL Script Not Joining Results

I am having an issue getting this SQL Script to join the two tables together, I can execute it and it will show the results of the first portion (AccountID, AuditDate ..etc) but it will not join to the inner select statement.
I have verified by spot checking that there is data that matches in the database.
What portion did i mess up?
Select AccountID, AuditDate, SourceVersion
From Audit
Left join (
Select A.PrinterAuditID, A.AuditID, A.SerialNr, A.PageCountTotal,a.PageCountColor, A.PageCountMono
from InvalidPrinterAudit A
where A.DeviceID = 90757
) InvalidPrinterAudit on InvalidPrinterAudit.AuditID = Audit.AuditID
There's a couple of things happening here.
One: In order to have fields in your result set, they must be included in the SELECT portion of your query:
Select AccountID, AuditDate, SourceVersion, InvalidPrinterAudit.PrinterAuditID, InvalidPrinterAudit.AuditID, InvalidPrinterAudit.SerialNr, InvalidPrinterAudit.PageCountTotal,InvalidPrinterAudit.PageCountColor, InvalidPrinterAudit.PageCountMono
From Audit
Left join (
Select A.PrinterAuditID, A.AuditID, A.SerialNr, A.PageCountTotal,a.PageCountColor, A.PageCountMono
from InvalidPrinterAudit A
where A.DeviceID = 90757
) InvalidPrinterAudit on InvalidPrinterAudit.AuditID = Audit.AuditID
Two: You don't need to have a subquery here. Subqueries are great if you need to aggregate the results from a seperate table or something, but here you can just go with a LEFT OUTER JOIN and be done with it.
Select AccountID, AuditDate, SourceVersion, InvalidPrinterAudit.PrinterAuditID, InvalidPrinterAudit.AuditID, InvalidPrinterAudit.SerialNr, InvalidPrinterAudit.PageCountTotal,InvalidPrinterAudit.PageCountColor, InvalidPrinterAudit.PageCountMono
From Audit
Left OUTER JOIN InvalidPrinterAudit
ON InvalidPrinterAudit.AuditID = Audit.AuditID
AND InvalidPrinterAudit.DeviceID = 90757
This will apply that DeviceID = 90757 filter to your InvalidPrinterAudit before the join is applied, so you'll still get all of your Audit records, and then only the InvalidPrinterAudit records for that DeviceID that matches.
You are selecting less columns in the outer query than in the inner query.
If you want them to be returned in the resultset, include them in the outer:
Select AccountID, AuditDate, SourceVersion, PrinterAuditID, SerialNr
From Audit
Left join (
Select A.PrinterAuditID, A.AuditID, A.SerialNr, A.PageCountTotal,a.PageCountColor, A.PageCountMono
from InvalidPrinterAudit A
where A.DeviceID = 90757
) InvalidPrinterAudit on InvalidPrinterAudit.AuditID = Audit.AuditID

Remove duplicate SQL Join results

Okay, I and totally new to SQL so bear with me. I created a statement which I have the results I wanted but wanted get rid of duplicate results. What's a easy solution to this? Here is my statement
SELECT
li.location,
li.logistics_unit,
li.item,
li.company,
li.item_desc,
li.on_hand_qty,
li.in_transit_qty,
li.allocated_qty,
li.lot,
i.item_category3,
location.locating_zone,
location.location_subclass,
i.item_category4
FROM
location_inventory li
INNER JOIN item i ON li.item = i.item
INNER JOIN location l ON l.location = li.location
WHERE
i.item_category3 = 'AS' AND
li.warehouse = 'river' AND
li.location NOT LIKE 'd%' AND
li.location NOT LIKE 'stg%'
ORDER BY
li.item asc
If you are confident in your JOIN then DISTINCT should do the trick like so:
select DISTINCT
location_inventory.location ,
location_inventory.logistics_unit ,
location_inventory.item ,
location_inventory.company ,
location_inventory.item_desc ,
location_inventory.on_hand_qty ,
location_inventory.in_transit_qty ,
location_inventory.allocated_qty ,
location_inventory.lot ,
item.item_category3 ,
location.locating_zone ,
location.location_subclass ,
item.item_category4
from location_inventory
INNER JOIN item
on location_inventory.item=item.item
INNER JOIN location
on location_inventory.location=location.location
where item.item_category3 = 'AS' and
location_inventory.warehouse = 'river' and
location_inventory.location not like 'd%' and
location_inventory.location not like 'stg%'
order by location_inventory.item asc
Assuming that i.item and l.location are primary or unique keys, any duplicates you see are being caused by duplicate items in your location_inventory table. That might or might not be what you want.
SELECT DISTINCT will only eliminate true duplicates (i.e. those where all of the selected columns are duplicate). If that's what you want, use it. Otherwise, you might need to make an inner select that uses SELECT DISTINCT to identify the columns in which you don't want duplicates, and join the results of the inner select back to the tables to pull out all the other data.

Joining two tables on a key and then left outer joining a table on a number of criteria

I'm attempting to join 3 tables together in a single query. The first two have a key so each entry has a matching entry. This joined table will then be joined by a third table that could produce multiple entries for each entry from the first table (the joined ones).
select * from
(select a.bidentifier, a.bsession, a.symbol, b.jidentifier, b.JSession
from trade_monthly a, trade_monthly_second b
where
a.bidentifier = b.jidentifier AND
a.bsession = b.JSession)
left outer join
trade c
on c.symbol = a.symbol
order by a.bidentifier, a.bsession, a.symbol, b.jidentifier, b.JSession, c.symbol
There will be more criteria (not just c.symbol = a.symbol) on the left outer join but for now this should be useful. How can I nest the queries this way? I'm gettin gan SQL command not properly ended error.
Any help is appreciated.
Thanks
For what I know every derived table must be given a name; so try something like this:
SELECT * FROM
(SELECT a.bidentifier, ....
...
a.bsession = b.JSession) t
LEFT JOIN trade c
ON c.symbol = t.symbol
ORDER BY t.bidentifier, ...
Anyway I think you could use a simpler query:
SELECT a.bidentifier, a.bsession, a.symbol, b.jidentifier, b.JSession, c.*
FROM trade_monthly a
INNER JOIN trade_monthly_second b
ON a.bidentifier = b.jidentifier
AND a.bsession = b.JSession
LEFT JOIN trade c
ON c.symbol = a.symbol
ORDER BY a.bidentifier, a.bsession, a.symbol, b.jidentifier, b.JSession, c.symbol
Try this:
SELECT
`trade_monthly`.`bidentifier` AS `bidentifier`,
`trade_monthly`.`bsession` AS `bsession`,
`trade_monthly`.`symbol` AS `symbol`,
`trade_monthly_second`.`jidentifier` AS `jidentifier`,
`trade_monthly_second`.`jsession` AS `jsession`
FROM
(
(
`trade_monthly`
JOIN `trade_monthly_second` ON(
(
(
`trade_monthly`.`bidentifier` = `trade_monthly_second`.`jidentifier`
)
AND(
`trade_monthly`.`bsession` = `trade_monthly_second`.`jsession`
)
)
)
)
JOIN `trade` ON(
(
`trade`.`symbol` = `trade_monthly`.`symbol`
)
)
)
ORDER BY
`trade_monthly`.`bidentifier`,
`trade_monthly`.`bsession`,
`trade_monthly`.`symbol`,
`trade_monthly_second`.`jidentifier`,
`trade_monthly_second`.`jsession`,
`trade`.`symbol`
Why don't you just create a view of the two inner joined tables. Then you can build a query that joins this view to the trade table using the left outer join matching criteria.
In my opinion, views are one of the most overlooked solutions to a lot of complex queries.