Sql Outer Join: Extracting values from multible tables - sql

I am extracting data from multiple tables. mt query is as follows:
SELECT p.Record_Num as RecordNum
,p.GCD_ID as GCDID
,p.Project_Desc as ProjectDesc
,p.Proponent_Name as ProponentName
,st.Station_Name as StationName
,p.OpCentre as OpCentre
,s.Sector_Name as SectorName
,p.PLZone as PLZone
,f.Feeder_Desc as FeederDesc
,d.DxTx_Desc as DxTx
,op.Op_Control_Desc as OpControl
,t.Type_Desc as Type
,c.Conn_Desc as ConnectionKV
,ss.Status_Desc as Status
,p.MW as MW
,p.Subject as Subject
,p.Ip_Num as IpNum
,p.H1N_ID as H1NID
,p.NOMS_Slip_Num as NomsSlipNum
,p.NMS_Updated as NmsUpdated
,p.Received_Date as ReceivedDate
,p.Actual_IS_Date as ActualISDate
,p.Scheduled_IS_Date as ScheduledIsDate
,stst.Station_Name as UpStation
,ff.Feeder_Desc as UpFeeder
,p.HV_Circuit as HVCircuit
,p.SIA_Required as SIAReqd
FROM Project_Detail p,
Station st, Sector s, Feeder f, DxTx d, Operational_Control op, Type t,
Connection_Kv c, Status ss, Station stst, Feeder ff
WHERE
p.Station_ID = st.Station_ID and
p.Sector_ID = s.Sector_ID and
p.Feeder = f.Feeder_ID and
p.DxTx_ID = d.DxTx_ID and
p.OpControl_ID = op.Op_Control_ID and
p.Type_ID= t.Type_ID and
p.ConnKV_ID = c.Conn_ID and
p.Status_ID = ss.Status_ID and
p.UP_Station_ID = stst.Station_ID and
p.UP_Feeder_ID = ff.Feeder_ID
The problem with this query is if it doesnot find an associated value in the second table, it doesnot show the row.
for example : every project has feeders. so if a project_detail table has a feederid which doesnot have an association in the feeder table, then it wont show the row. also, there are times when the feeders are not assigned to a project.
i think i have to use outer joins to get the values. but i cannot figure out how to do that.
please help.

SELECT *
FROM Project_Detail p
LEFT JOIN
Station st
ON p.Station_ID = st.Station_ID
LEFT JOIN
Sector s
ON p.Sector_ID = s.Sector_ID
…

You need LEFT OR FULL OUTER JOINS instead of the inner joins you are now using with your where clause.
SELECT p.Record_Num as RecordNum
,p.GCD_ID as GCDID
,p.Project_Desc as ProjectDesc
,p.Proponent_Name as ProponentName
,st.Station_Name as StationName
,p.OpCentre as OpCentre
,s.Sector_Name as SectorName
,p.PLZone as PLZone
,f.Feeder_Desc as FeederDesc
,d.DxTx_Desc as DxTx
,op.Op_Control_Desc as OpControl
,t.Type_Desc as Type
,c.Conn_Desc as ConnectionKV
,ss.Status_Desc as Status
,p.MW as MW
,p.Subject as Subject
,p.Ip_Num as IpNum
,p.H1N_ID as H1NID
,p.NOMS_Slip_Num as NomsSlipNum
,p.NMS_Updated as NmsUpdated
,p.Received_Date as ReceivedDate
,p.Actual_IS_Date as ActualISDate
,p.Scheduled_IS_Date as ScheduledIsDate
,stst.Station_Name as UpStation
,ff.Feeder_Desc as UpFeeder
,p.HV_Circuit as HVCircuit
,p.SIA_Required as SIAReqd
FROM Project_Detail p
LEFT OUTER JOIN Station st ON p.Station_ID = st.Station_ID
LEFT OUTER JOIN Sector s ON p.Sector_ID = s.Sector_ID
LEFT OUTER JOIN Feeder f ON p.Feeder = f.Feeder_ID
LEFT OUTER JOIN DxTx d ON p.DxTx_ID = d.DxTx_ID
LEFT OUTER JOIN Operational_Control op ON p.OpControl_ID = op.Op_Control_ID
LEFT OUTER JOIN Type t ON p.Type_ID= t.Type_ID
LEFT OUTER JOIN Connection_Kv c ON p.ConnKV_ID = c.Conn_ID
LEFT OUTER JOIN Status ss ON p.Status_ID = ss.Status_ID
LEFT OUTER JOIN Station stst ON p.UP_Station_ID = stst.Station_ID
LEFT OUTER JOIN Feeder ff ON p.UP_Feeder_ID = ff.Feeder_ID

Related

Select statement where joins causing records to be excluded

I have the below query with multiple joins.The last 3 joins are required to get the g.fin_id value. This works fine (see results) BUT because some records in the ACCUM_ISS_CHAR_HIST table have e.char9_nme values of NULL, it excludes the records in the results altogether. So it seems as when the e.char9_nme value has a record then it will produce a result, but as soon as it has a Null value then it is excluded. I would still like to see the records even though the g.fin_id for those will then be blank because they have a e.char9_nme value of Null. How can I change the query to accomplish this?
select
a.acct_id,
c.fld3_txt,
b.issue_loc1_cde,
b.instr_id,
a.fld1_nme,
b.issue_cls2_nme,
g.fin_id,
e.char9_nme
from position_dg as a
inner join
infoportal..issue_dg as b on b.INSTR_ID = a.INSTR_ID
inner join
InfoPortal..IVW_ACCT as c on a.acct_id = c.acct_id
inner join
InfoPortal..DW_AcctCharDG as d on a.acct_id = d.acctid
inner join
ACCUM_ISS_CHAR_HIST as e on a.instr_id = e.instr_id
inner join
MD_FINANCIAL_ENTITY as f on e.char9_nme = f.fin_enty_name
inner join md_FINANCIAL_ENTITY_ALTERNATE_IDENTIFIER as g on
f.fin_enty_id = g.fin_enty_id
and b.MAT_EXP_DTE > getdate()
and b.issue_cls1_nme = 'Derivatives'
and a.as_of_tms >= getdate()-1
and b.iss_typ in ('FFX','IRS','EQF')
and d.AcctChrSetId = 'DerivativeRpt'
and d.EndTms IS NULL
and a.acct_id = 'FOGEMBLCR'
and g.id_ctxt_typ = 'LEGAL_ENTITY_IDENTIFIER'
and e.as_of_dte = (
select MAX (as_of_dte)-1
from accum_iss_char_hist
)
I expect the results to show fin_id records for some ond blank fin_id records for some, but at the moment only the ones with a fin_id record is hown and the rest is excluded from the results.
You are looking for a left join.
Join all those tables (last 3 as you said) as left join. For better clarity I have moved conditions of every tables in their ON clause and for base table a made a where clause.
select
a.acct_id,
c.fld3_txt,
b.issue_loc1_cde,
b.instr_id,
a.fld1_nme,
b.issue_cls2_nme,
g.fin_id,
e.char9_nme
from position_dg as a
inner join
infoportal..issue_dg as b on b.INSTR_ID = a.INSTR_ID
and b.MAT_EXP_DTE > getdate()
and b.issue_cls1_nme = 'Derivatives'
and b.iss_typ in ('FFX','IRS','EQF')
inner join
InfoPortal..IVW_ACCT as c on a.acct_id = c.acct_id
inner join
InfoPortal..DW_AcctCharDG as d on a.acct_id = d.acctid
and d.AcctChrSetId = 'DerivativeRpt'
and d.EndTms IS NULL
left join
ACCUM_ISS_CHAR_HIST as e on a.instr_id = e.instr_id
and e.as_of_dte = (
select MAX (as_of_dte)-1
from accum_iss_char_hist
)
left join
MD_FINANCIAL_ENTITY as f on e.char9_nme = f.fin_enty_name
left join
md_FINANCIAL_ENTITY_ALTERNATE_IDENTIFIER as g on f.fin_enty_id = g.fin_enty_id
and g.id_ctxt_typ = 'LEGAL_ENTITY_IDENTIFIER'
Where a.as_of_tms >= getdate()-1
and a.acct_id = 'FOGEMBLCR'

Looking to add in a Count query with Group by INTO an existing working query

Goal:
I wish to get the Count of how many times a WorkItem was re-assigned
From what I understand the proper query is the following:
SELECT
WorkItemDimvw.Id,
COUNT(WorkItemAssignedToUserFactvw.WorkItemAssignedToUser_UserDimKey) AS Assignments
FROM WorkItemDimvw INNER JOIN WorkItemAssignedToUserFactvw
ON WorkItemDimvw.WorkItemDimKey = WorkItemAssignedToUserFactvw.WorkItemDimKey
GROUP BY WorkItemDimvw.Id
The EXISTING query is below and I'm wondering / forgeting if I should:
Just add in COUNT(WorkItemAssignedToUserFactvw.WorkItemAssignedToUser_UserDimKey) AS Assignments since joins are existing, except it is group by WorkItemDimvw.Id
Should it instead be a subquery in the Select below?
Query:
SELECT
SRD.ID,
SRD.Title,
SRD.Description,
SRD.EntityDimKey,
WI.WorkItemDimKey,
IATUFact.DateKey
FROM
SLAConfigurationDimvw
INNER JOIN SLAInstanceInformationFactvw
ON SLAConfigurationDimvw.SLAConfigurationDimKey = SLAInstanceInformationFactvw.SLAConfigurationDimKey
RIGHT OUTER JOIN ServiceRequestDimvw AS SRD
INNER JOIN WorkItemDimvw AS WI
ON SRD.EntityDimKey = WI.EntityDimKey
LEFT OUTER JOIN WorkItemAssignedToUserFactvw AS IATUFact
ON WI.WorkItemDimKey = IATUFact.WorkItemDimKey
AND IATUFact.DeletedDate IS NULL
The trick is to aggregate the data on a sub query, before you join it.
SELECT
SRD.ID,
SRD.Title,
SRD.Description,
SRD.EntityDimKey,
WI.WorkItemDimKey,
IATUFact.DateKey,
IATUFact.Assignments
FROM
SLAConfigurationDimvw
INNER JOIN
SLAInstanceInformationFactvw
ON SLAConfigurationDimvw.SLAConfigurationDimKey = SLAInstanceInformationFactvw.SLAConfigurationDimKey
RIGHT OUTER JOIN
ServiceRequestDimvw AS SRD
ON <you're missing something here>
INNER JOIN
WorkItemDimvw AS WI
ON SRD.EntityDimKey = WI.EntityDimKey
LEFT OUTER JOIN
(
SELECT
WorkItemDimKey,
DateKey,
COUNT(WorkItemAssignedToUser_UserDimKey) AS Assignments
FROM
WorkItemAssignedToUserFactvw
WHERE
DeletedDate IS NULL
GROUP BY
WorkItemDimKey,
DateKey
)
IATUFact
ON WI.WorkItemDimKey = IATUFact.WorkItemDimKey

SQL-Get and replace minimum value of a query's field

I have the following query in Postgresql :
SELECT mq.nombre,sa.nombre,COUNT(DISTINCT(ae.numero_serie)),SUM(im.fin-im.inicio),MIN(pz.fecha_inicio)
FROM item_metraje AS im LEFT JOIN articulo_especificado AS ae ON (im.id_articulo_especificado = ae.id)
LEFT JOIN articulo AS a ON (ae.id_articulo = a.id)
LEFT JOIN serie_articulo AS sa ON (a.id_serie_articulo = sa.id)
LEFT JOIN reporte_perforacion AS rp ON (rp.id = im.id_reporte_perforacion)
LEFT JOIN pozo AS pz ON (pz.id=rp.id_pozo) LEFT JOIN proyecto AS p ON (p.id=pz.id_proyecto)
LEFT JOIN maquina_perforacion AS mq ON (mq.id = pz.id_maquina)
WHERE p.id = 2 GROUP BY mq.nombre,sa.nombre
and the result is :
However I want to put the minimum date for the rows that have the same value of the field 'nombre', for example for the value 'JM04' the three rows must have the date 2015-01-25 because it is the minimum value of the three rows.
Excuse me for my English and thanks for all.
You can use Window functions for this purpose. MIN(pz.fecha_inicio) over (partition by mq.nombre).
Therefore the final query is,
SELECT z.nombre1,z.nombre2,z.count,z.sum ,MIN(z.date) over (partition by z.nombre1) from
(SELECT mq.nombre as nombre1 ,sa.nombre as nombre2,COUNT(DISTINCT(ae.numero_serie)) as count,SUM(im.fin-im.inicio) as sum ,pz.fecha_inicio as date
FROM item_metraje AS im LEFT JOIN articulo_especificado AS ae ON (im.id_articulo_especificado = ae.id)
LEFT JOIN articulo AS a ON (ae.id_articulo = a.id)
LEFT JOIN serie_articulo AS sa ON (a.id_serie_articulo = sa.id)
LEFT JOIN reporte_perforacion AS rp ON (rp.id = im.id_reporte_perforacion)
LEFT JOIN pozo AS pz ON (pz.id=rp.id_pozo) LEFT JOIN proyecto AS p ON (p.id=pz.id_proyecto)
LEFT JOIN maquina_perforacion AS mq ON (mq.id = pz.id_maquina)
WHERE p.id = 2 GROUP BY mq.nombre,sa.nombre)z
You can modify this with the help of order by or having clauses inside window function as you want. I tried this with my own data set. Hope this helps.

Avoiding NULL records on this LEFT JOIN

The query below works - EXCEPT - it is returning NULL values for vehicle_id. I do not want any records that have NULL for vehicle_id.
Since vehicle_id is tied to fund_series, this is complicated to me.
When I had the vehicle_id conditions underneath the WHERE, the query was not working. Any SQL geniuses that can help?
I put the MIN() aggregate functions in there just so I could get the GROUP BY to work.
SELECT DISTINCT
MIN(ml.pretty_file_name),
ml.filename,
MIN(ml.issued_date),
MIN(mr.rule_name),
MIN(mlob.line_of_business_name),
MIN(mt.media_type_name),
MAX(v.vehicle_name)
FROM Media_Live ml
JOIN Media_Type mt
ON mt.media_type_id = ml.media_type_id
JOIN Media_Rule mr
ON mr.rule_id = ml.rule_id
JOIN Media_Line_Of_Business mlob
ON mlob.line_of_business_id = ml.line_of_business_id
LEFT JOIN Fund_Class_Media fcm
ON fcm.media_id=ml.media_id
LEFT JOIN Fund_Class_Live fc
ON fc.fund_class_id = fcm.fund_class_id
LEFT JOIN Fund_Series fs
ON fs.fund_series_id = fc.fund_series_id
LEFT JOIN Vehicle AS v
ON v.vehicle_id=fs.vehicle_id AND /*THIS IS WHERE IM GETTING NULLS*/
(
v.vehicle_id = 1
OR v.vehicle_id = 2
OR v.vehicle_id = 5
)
LEFT JOIN Media_Media_Tag AS mmt ON mmt.media_id=ml.media_id
LEFT JOIN Media_Tag AS mtag ON mtag.tag_id=mmt.tag_id
WHERE
(/*people can search with terms for fc*/
--fc.fund_class_id LIKE '%'+replace(?,' ','%')+'%'
)
(
mt.media_type_id = 33
OR mt.media_type_id = 1
OR mt.media_type_id = 12
)
AND
(
mr.rule_id = 3
OR mr.rule_id = 9
)
AND
(
mtag.tag_name != 'exclude_web_lit_center'
)
GROUP BY ml.filename
This is what a left join does, allow nulls. Just take out the left join part making it an inner join.
JOIN Vehicle AS v ON v.vehicle_id=fs.vehicle_id AND v.vehicle_id IN (1,2,5)
You cold also do this, but I don't see why you would:
LEFT JOIN Vehicle AS v ON v.vehicle_id=fs.vehicle_id AND ISNULL(v.vehicle_id,0) IN (1,2,5)
In the WHERE clause, add:
AND v.Vehicl_Id IS NOT NULL
That should do it.

SQL with left outer join and 3 tables

I would like to add an ADD at the end of my code. Please have a look on my code and thanks for your support:
SELECT Area.org,
Supervisors.NomSup,
Supervisors.PrenomSup,
Employees.NomEmp,
Employees.PrenomEmp,
Employees.NoIdAlcanEmp,
Competencies.CodeCompetencies,
Competencies.CompetencyName,
LinkResultComp.AssNote,
LinkResultComp.AssDate
FROM ((((((
Area INNER JOIN Supervisors ON Area.IdArea = Supervisors.IdArea
)
INNER JOIN Employees ON Supervisors.IdSupervisor = Employees.IdSupervisor
)
INNER JOIN LinkProfilesEmployees ON Employees.IdEmp = LinkProfilesEmployees.IdEmp
)
INNER JOIN Profiles ON Profiles.IdProfiles = LinkProfilesEmployees.IdProfiles
)
INNER JOIN LinkProfComp ON Profiles.IdProfiles = LinkProfComp.IdProfiles
)
INNER JOIN Competencies ON Competencies.IdCompetencies = LinkProfComp.IdCompetencies
)
LEFT OUTER JOIN LinkResultComp ON (Competencies.IdCompetencies = LinkResultComp.IdCompetencies AND ON Competencies.IdCompetencies = LinkResultComp.IdCompetencies)
WHERE Area.org LIKE "*20*" AND Competencies.CodeCompetencies LIKE "khse2010-05"
ORDER BY Supervisors.NomSup, Employees.NomEmp;
Just remove the extra ON that you added
So change this
LEFT OUTER JOIN LinkResultComp
ON (Competencies.IdCompetencies = LinkResultComp.IdCompetencies
AND ON Competencies.IdCompetencies = LinkResultComp.IdCompetencies)
------^^ This one
to this
LEFT OUTER JOIN LinkResultComp
ON (Competencies.IdCompetencies = LinkResultComp.IdCompetencies
AND Competencies.IdCompetencies = LinkResultComp.IdCompetencies)
Of course I assume you meant different fields for the second condition