How can I do a SQL join to get a value 4 tables farther from the value provided? - sql

My title is probably not very clear, so I made a little schema to explain what I'm trying to achieve. The xxxx_uid labels are foreign keys linking two tables.
Goal: Retrieve a column from the grids table by giving a proj_uid value.
I'm not very good with SQL joins and I don't know how to build a single query that will achieve that.
Actually, I'm doing 3 queries to perform the operation:
1) This gives me a res_uid to work with:
select res_uid from results where results.proj_uid = VALUE order by res_uid asc limit 1"
2) This gives me a rec_uid to work with:
select rec_uid from receptor_results
inner join results on results.res_uid = receptor_results.res_uid
where receptor_results.res_uid = res_uid_VALUE order by rec_uid asc limit 1
3) Get the grid column I want from the grids table:
select grid_name from grids
inner join receptors on receptors.grid_uid = grids.grid_uid
where receptors.rec_uid = rec_uid_VALUE;
Is it possible to perform a single SQL that will give me the same results the 3 I'm actually doing ?

You're not limited to one JOIN in a query:
select grids.grid_name
from grids
inner join receptors
on receptors.grid_uid = grids.grid_uid
inner join receptor_results
on receptor_results.rec_uid = receptors.rec_uid
inner join results
on results.res_uid = receptor_results.res_uid
where results.proj_uid = VALUE;

select g.grid_name
from results r
join resceptor_results rr on r.res_uid = rr.res_uid
join receptors rec on rec.rec_uid = rr.rec_uid
join grids g on g.grid_uid = rec.grid_uid
where r.proj_uid = VALUE
a small note about names, typically in sql the table is named for a single item not the group. thus "result" not "results" and "receptor" not "receptors" etc. As you work with sql this will make sense and names like you have will seem strange. Also, one less character to type!

Related

Group by concat in SQL Server

I’m using multiple joins for a specific logic , but encountered a problem . Some of the records has 1-2 relation in one of the tables which mess up my output. I want to concat all these string so it will appear it one record, but I don’t know how to do it in sql server . In oracle and MySQL it’s easy but I tried playing with online examples and failed miserably.
My query:
SELECT c.customerName,c.Guid,p.campaignTitle ,
(SELECT k.campaignTitle FROM [DEV_TEST2].[dbo].campaigns l JOIN [DEV_TEST2].[dbo].campaignstitle k on k.campaignname = l.campaignname where l.campaignid = t.referrerurl) as Referrertitle,
t.activitydate,t.type
FROM [DEV_TEST2].[dbo].campaignknowncustomers c
join [DEV_TEST2].[dbo].[CampaignCustomerMatch] t ON(c.guid = t.visitorexternalid)
join [DEV_TEST2].[dbo].campaigns s ON(t.url = s.campaignid)
join [DEV_TEST2].[dbo].campaignstitle p on(s.campaignname = p.campaignname)
order by customername,activitydate
My problem is with campaigntitle column and referrertitle correlated query. Both come from the same table. I need to concat it and show only 1 row per ‘customername, guid, activitydate’

JOIN EXPRESSION NOT SUPPORTED with 3 tables

I'm working with MS Access, trying to join 3 tables together. But i'm getting message "JOIN EXPRESSION NOT SUPPORTED.".
Basically I want to join just 2 tables which are A_01HWeekEHCalendar and A00_Plant. A00_Plant requires 3 column to join; Plant_Product, Plant_Code, and Plant_Name. Plant_Product, Plant_Code is ok, but there is no column to match Plant_Product. so I have to add A_ProductGroup
I'm not sure if it can't be done in one Query or it's error from my SYNTAX. or there will be another way to do that without separate Queries.
I also add a picture of what I want and try to run and get error.
Thanks.
SELECT
A_01HWeekEHCalendar.RunNo_H,
A_01HWeekEHCalendar.Audit_Week,
A_01HWeekEHCalendar.CurrentYear,
A_01HWeekEHCalendar.CurrentWeek,
A_01HWeekEHCalendar.TTSMonth,
A_01HWeekEHCalendar.Audit_Plant,
A_01HWeekEHCalendar.Audit_plantname,
A_01HWeekEHCalendar.Audit_Qacode,
A_01HWeekEHCalendar.Audit_Qaname,
A_01HWeekEHCalendar.Audit_Product,
A00_Plant.HCA_StartDate
FROM
(A_01HWeekEHCalendar LEFT JOIN A_ProductGroup
ON A_01HWeekEHCalendar.Audit_Product = A_ProductGroup.R_Code)
LEFT JOIN A00_Plant
ON A_01HWeekEHCalendar.Audit_plantname = A00_Plant.Plant_Name
AND A_01HWeekEHCalendar.Audit_Plant = A00_Plant.Plant_Code
AND A_ProductGroup.R_Code = A00_Plant.Plant_Product;
You are lucky because you want only one column. You can work around this problem using a correlated subquery:
SELECT . . .,
(SELECT TOP (1) A00_Plant.HCA_StartDate
FROM A00_Plant
WHERE A_01HWeekEHCalendar.Audit_plantname = A00_Plant.Plant_Name
AND
A_01HWeekEHCalendar.Audit_Plant = A00_Plant.Plant_Code AND
A_ProductGroup.R_Code = A00_Plant.Plant_Product
) as HCA_StartDate
FROM A_01HWeekEHCalendar LEFT JOIN
A_ProductGroup
ON A_01HWeekEHCalendar.Audit_Product = A_ProductGroup.R_Code ;

COUNT is outputting more than one row

I am having a problem with my SQL query using the count function.
When I don't have an inner join, it counts 55 rows. When I add the inner join into my query, it adds a lot to it. It suddenly became 102 rows.
Here is my SQL Query:
SELECT COUNT([fmsStage].[dbo].[File].[FILENUMBER])
FROM [fmsStage].[dbo].[File]
INNER JOIN [fmsStage].[dbo].[Container]
ON [fmsStage].[dbo].[File].[FILENUMBER] = [fmsStage].[dbo].[Container].[FILENUMBER]
WHERE [fmsStage].[dbo].[File].[RELATIONCODE] = 'SHIP02'
AND [fmsStage].[dbo].[Container].DELIVERYDATE BETWEEN '2016-10-06' AND '2016-10-08'
GROUP BY [fmsStage].[dbo].[File].[FILENUMBER]
Also, I have to do TOP 1 at the SELECT statement because it returns 51 rows with random numbers inside of them. (They are probably not random, but I can't figure out what they are.)
What do I have to do to make it just count the rows from [fmsStage].[dbo].[file].[FILENUMBER]?
First, your query would be much clearer like this:
SELECT COUNT(f.[FILENUMBER])
FROM [fmsStage].[dbo].[File] f INNER JOIN
[fmsStage].[dbo].[Container] c
ON v.[FILENUMBER] = c.[FILENUMBER]
WHERE f.[RELATIONCODE] = 'SHIP02' AND
c.DELIVERYDATE BETWEEN '2016-10-06' AND '2016-10-08';
No GROUP BY is necessary. Otherwise you'll just one row per file number, which doesn't seem as useful as the overall count.
Note: You might want COUNT(DISTINCT f.[FILENUMBER]). Your question doesn't provide enough information to make a judgement.
Just remove GROUP BY Clause
SELECT COUNT([fmsStage].[dbo].[File].[FILENUMBER])
FROM [fmsStage].[dbo].[File]
INNER JOIN [fmsStage].[dbo].[Container]
ON [fmsStage].[dbo].[File].[FILENUMBER] = [fmsStage].[dbo].[Container].[FILENUMBER]
WHERE [fmsStage].[dbo].[File].[RELATIONCODE] = 'SHIP02'
AND [fmsStage].[dbo].[Container].DELIVERYDATE BETWEEN '2016-10-06' AND '2016-10-08'

Optimize SQL query with many left join

I have a SQL query with many left joins
SELECT COUNT(DISTINCT po.o_id)
FROM T_PROPOSAL_INFO po
LEFT JOIN T_PLAN_TYPE tp ON tp.plan_type_id = po.Plan_Type_Fk
LEFT JOIN T_PRODUCT_TYPE pt ON pt.PRODUCT_TYPE_ID = po.cust_product_type_fk
LEFT JOIN T_PROPOSAL_TYPE prt ON prt.PROPTYPE_ID = po.proposal_type_fk
LEFT JOIN T_BUSINESS_SOURCE bs ON bs.BUSINESS_SOURCE_ID = po.CONT_AGT_BRK_CHANNEL_FK
LEFT JOIN T_USER ur ON ur.Id = po.user_id_fk
LEFT JOIN T_ROLES ro ON ur.roleid_fk = ro.Role_Id
LEFT JOIN T_UNDERWRITING_DECISION und ON und.O_Id = po.decision_id_fk
LEFT JOIN T_STATUS st ON st.STATUS_ID = po.piv_uw_status_fk
LEFT OUTER JOIN T_MEMBER_INFO mi ON mi.proposal_info_fk = po.O_ID
WHERE 1 = 1
AND po.CUST_APP_NO LIKE '%100010233976%'
AND 1 = 1
AND po.IS_STP <> 1
AND po.PIV_UW_STATUS_FK != 10
The performance seems to be not good and I would like to optimize the query.
Any suggestions please?
Try this one -
SELECT COUNT(DISTINCT po.o_id)
FROM T_PROPOSAL_INFO po
WHERE PO.CUST_APP_NO LIKE '%100010233976%'
AND PO.IS_STP <> 1
AND po.PIV_UW_STATUS_FK != 10
First, check your indexes. Are they old? Did they get fragmented? Do they need rebuilding?
Then, check your "execution plan" (varies depending on the SQL Engine): are all joins properly understood? Are some of them 'out of order'? Do some of them transfer too many data?
Then, check your plan and indexes: are all important columns covered? Are there any outstandingly lengthy table scans or joins? Are the columns in indexes IN ORDER with the query?
Then, revise your query:
- can you extract some parts that normally would quickly generate small rowset?
- can you add new columns to indexes so join/filter expressions will get covered?
- or reorder them so they match the query better?
And, supporting the solution from #Devart:
Can you eliminate some tables on the way? does the where touch the other tables at all? does the data in the other tables modify the count significantly? If neither SELECT nor WHERE never touches the other joined columns, and if the COUNT exact value is not that important (i.e. does that T_PROPOSAL_INFO exist?) then you might remove all the joins completely, as Devart suggested. LEFTJOINs never reduce the number of rows. They only copy/expand/multiply the rows.

SQL - Query Select Joins through multiple tables

Here is the situation:
I search for Persons with ID (empr.empr_cb)
that has bill(s) to pay (transactions.montant)
this refers to transactions.compte_id
which is identical to comptes.id_compte
this refers to comptes.proprio.id
which is identical to empr.id_empr
that would give us the Person ID (empr.empr_cb)
I tried this, but I don't know what joins to set (cross Join?):
SELECT `empr`.`empr_cb`,`transactions`.`montant`
FROM `empr`,`comptes`,`transactions`
WHERE `transactions`.`montant` > `0`
AND `transactions`.`encaissement` = `0`
AND `transactions`.compte_id` = `comptes`.`id_compte`
AND `comptes`.`proprio_id` = `id_empr`
Any ideas how to put the joins?
This query is already using implicit INNER JOINs. It can be rewritten this way:
SELECT empr.empr_cb
, transactions.montant
FROM empr
JOIN comptes ON comptes.proprio_id = empr.id_empr
JOIN transactions ON transactions.compte_id = comptes.id_compte
WHERE transactions.encaissement = 0
AND transactions.montant > 0