Why is this SQL query returning this result? - sql

Can anyone tell me why this sql query is returning this result.
SELECT
M.MatterNumber_Id, M.MatterNumber, M.MatterName,
ISNULL(MP.Role_Cd, 'No Primary') AS PrimaryRole,
ISNULL(E.Name, 'No Primary') AS PrimaryName,
ISNULL(C.CommNumber, 'l.w#abc.ca;m.j#abc.com') AS Email
FROM
Matter M
LEFT OUTER JOIN
MatterPlayer MP ON M.MatterNumber_Id = MP.MatterNumber_Id AND
MP.Role_Cd IN ('Primary Lawyer', 'Primary Staff Member') AND
MP.EndDate IS NULL
LEFT OUTER JOIN
Entity E on MP.Entity_EID = E.Entity_EID
LEFT OUTER JOIN Communication C on MP.Entity_EID = C.Entity_EID AND
C.CommunicationType_Cd = 'Email'
LEFT OUTER JOIN
MatterExposure ME on M.MatterNumber_Id = ME.MatterNumber_Id AND
ME.AssessedDate > '7/10/2014' AND
ME.Currency_CD IS NOT NULL
WHERE
M.MatterStatus_Cd = 'Active' AND
ME.AssessedDate IS NULL AND
M.Matter_Cd in
(SELECT
rpl.Type_CD
FROM
RuleProfile_Tabs rpt
INNER JOIN
RuleProfile_LookupCode rpl ON rpt.RuleProfile_ID = rpl.RuleProfile_ID
WHERE
tab_id = 1034 AND Caption LIKE 'Reportable Matter%')
ORDER BY
Email, M.MatterName
But When i see the results I check one of the records returned and it should not have been returned.
One of the results returned:
Bailey, Richard
In the db i check the values in the tables it should not have been returned because Currency_CD is null and in the sql it states currency_cd is not null. Also the assessed date is AFTER 7/10/2014
Table Values:
MatterStatus_CD:
Active
AssessedDate:
7/24/2014
Currency_CD:
NULL
EndDate:
NULL

Where clauses are used for filtering, not the join clause. Every JOIN should have an ON. Here's a head start.
Select M.MatterNumber_Id, M.MatterNumber, M.MatterName,
IsNull(MP.Role_Cd, 'No Primary') as PrimaryRole,
IsNull(E.Name, 'No Primary') as PrimaryName,
IsNull(C.CommNumber, 'l.w#abc.ca;m.j#abc.com') as Email
From Matter M
Left Outer Join MatterPlayer MP on M.MatterNumber_Id = MP.MatterNumber_Id
Left Outer Join Entity E on MP.Entity_EID = E.Entity_EID
Left Outer Join Communication C on MP.Entity_EID = C.Entity_EID
Left Outer Join MatterExposure ME on M.MatterNumber_Id = ME.MatterNumber_Id
Where M.MatterStatus_Cd = 'Active'
AND ME.AssessedDate is Null
and M.Matter_Cd in (select rpl.Type_CD
from RuleProfile_Tabs rpt
inner join RuleProfile_LookupCode rpl on rpt.RuleProfile_ID = rpl.RuleProfile_ID
where tab_id = 1034 AND Caption like 'Reportable Matter%')
and MP.Role_Cd In ('Primary Lawyer', 'Primary Staff Member')
and MP.EndDate is Null
and ME.AssessedDate > '7/10/2014'
and ME.Currency_CD IS NOT NULL
and C.CommunicationType_Cd = 'Email'
Order by Email, M.MatterName

You are LEFT JOINing MatterExposure onto Matter. Your Me.Currency_CD IS NOT NULL criteria in the LEFT JOIN's ON statement is only saying, "don't join to records where Currency_CD is null..." but because this is a left join, none of your Matter table's records are lost in the join. So when you ask for Currency_CD you will get NULL.
To remove records from your query where Currency_CD is null in the MatterExposure table you will either need to specify Currency_CD IS NOT NULL in your where statement (instead of your join) or will need to use an INNER JOIN to your MatterExposure table.

It is because this join is a LEFT OUTER JOIN. If you want to enforce this join make it an inner join. Or move that check to the WHERE clause.

Related

LEFT OUTER JOIN with isnull

This is a pretty straightforward LEFT OUTER JOIN, but I get zero returned rows:
SELECT All_varieties.*,variety_join.*
FROM All_varieties LEFT JOIN
variety_join
ON All_varieties.varietyID = variety_join.varietyID
WHERE (variety_join.sourceID = Null);
However, I am using a query All_varieties
SELECT plant.plantName, plant.plantGenus, plant.plantSpecies, variety.varietyLatin, variety.varietyEnglish, variety.varietyID
FROM plant LEFT JOIN
variety
ON plant.plantID = variety.plantID;
Is the problem maybe with the query All_varieties?
TABLES:
It should be variety_join.sourceID is null instead of variety_join.sourceID = Null
SELECT All_varieties.*,variety_join.*
FROM All_varieties LEFT JOIN
variety_join
ON All_varieties.varietyID = variety_join.varietyID
WHERE variety_join.sourceID is Null

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

Trying to get the right SQL Query (Joins)

I've been trying to join a couple tables to get the right result.
The problem is its returning some NULL values where this shouldn't be the case.
EP.ProductId, CreateDate, IsproductActivated and Subject are returning a Null Value.I've noticed it That DossierID and dossier will return a value when I make a right join as stated below.
Could anyone help me with my case?
SELECT
EP.ProductId AS [ProductId]
,MAX(EP.CreateDate) AS [CreateDate]
,EP.IsProductActivated AS [IsProductActivated]
,PC.EntityId AS [DossierID]
,PC.EntityDiscriminator AS [EntityDiscriminator]
,PDCP.Name AS [Subject]
,D.Name AS [Dossier]
FROM
[tblEntityProduct] AS EP
LEFT JOIN .tblPDCProduct AS PDCP
ON PDCP.id = EP.Productid
LEFT JOIN
[tblProductContainerContent] AS PCC
ON PCC.EntityProductId = EP.ProductId
RIGHT JOIN
[tblProductContainer] AS PC
ON PC.Id = PCC.Productcontainerid
LEFT JOIN
[tblDossier] AS D
ON D.Id = PC.Entityid
WHERE PC.EntityId = 2803
GROUP BY EP.Productid
,IsProductActivated
,EntityId
,EntityDiscriminator
,PDCP.name
,D.name
The picture below shows the result of the above query. I want the values it suppose to have instead of the NULL
use inner join to avoid getting null values, because The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is NULL from the right side, if there is no match. for right join opposite is true of left join
SELECT
EP.ProductId AS [ProductId]
,MAX(EP.CreateDate) AS [CreateDate]
,EP.IsProductActivated AS [IsProductActivated]
,PC.EntityId AS [DossierID]
,PC.EntityDiscriminator AS [EntityDiscriminator]
,PDCP.Name AS [Subject]
,D.Name AS [Dossier]
FROM
[tblEntityProduct] AS EP
JOIN .tblPDCProduct AS PDCP
ON PDCP.id = EP.Productid
JOIN
[tblProductContainerContent] AS PCC
ON PCC.EntityProductId = EP.ProductId
JOIN
[tblProductContainer] AS PC
ON PC.Id = PCC.Productcontainerid
JOIN
[tblDossier] AS D
ON D.Id = PC.Entityid
WHERE PC.EntityId = 2803
GROUP BY EP.Productid
,IsProductActivated
,EntityId
,EntityDiscriminator
,PDCP.name
,D.name
I hate right-joins. They are basically a REQUIRE THIS TABLE regardless of the others leading up to it. Instead, I reversed the query to put the REQUIRED Table in the first position, then LEFT-JOIN to the underlying. Now, based on the structure / join, I would THINK that you start with a product container -- will always exist. Each product container has stuff in it (ProductContainerContent). Then, each content item IS an entity product to get its description. Each container has its own Dossier which may (or not) be assigned at the time the container is being prepared. If I am accurate, most of the LEFT-JOINs should just be standard (inner) JOINs, but lets see what this does against your data.
SELECT
EP.ProductId,
MAX(EP.CreateDate) CreateDate,
EP.IsProductActivated,
PC.EntityId DossierID,
PC.EntityDiscriminator,
PDCP.Name Subject,
D.Name Dossier
FROM
tblProductContainer PC
LEFT JOIN tblProductContainerContent PCC
ON PC.Id = PCC.Productcontainerid
LEFT JOIN tblEntityProduct EP
ON PCC.EntityProductId = EP.ProductId
LEFT JOIN tblPDCProduct PDCP
ON EP.Productid = PDCP.id
LEFT JOIN tblDossier D
ON PC.Entityid = D.Id
WHERE
PC.EntityId = 2803
GROUP BY
EP.Productid,
IsProductActivated,
EntityId,
EntityDiscriminator,
PDCP.name,
D.name

Postgresql - Conditional Join if data exist

My current query show the data from the table called "Buque" and has some references from another tables. The problem is when i execute the query it never shows the result because it consumes too much memory i guess.
The current query i have
select buq.buq_codigo, tbu.tbu_codigo, tbu.tbu_nombre, pai.pai_codigo, pai.pai_nombre,
pue.pto_codigo, pue.pto_nombre, lin.lin_codigo, lin.lin_nombre, tra.tra_codigo,
tra.tra_nombre, buq.buq_nombre, buq.buq_des, buq.num_trb, buq.num_eslora,
buq.max_tons, buq.reg_lloyd, buq.buq_codigo1, buq.codigo_omi,
case buq.buq_estado when 'A' then 'Activo' else 'Inactivo' end as buq_estado
from publico.mae_buque as buq, publico.mae_tipbuque as tbu, publico.mae_pais as pai,
publico.mae_puerto as pue, publico.mae_linea as lin, publico.mae_trafico as tra
where buq.tbu_codigo = tbu.tbu_codigo or
buq.pai_codigo = pai.pai_codigo or
buq.pto_codigo = pue.pto_codigo or
buq.lin_codigo = lin.lin_codigo or
buq.tra_codigo = tra.tra_codigo
I also tried with inner joins but the problem is it returns me the data that meets the conditions of the joins. In other words, if the join has data to compare, returns the name, if not, show the null data.
The query must return me 611 records, with inner joins returns 68 records.
Concerning your desired result, use left outer joins, which fill up any non-existing rows of the right hand side table with null-values;
Concerning the out of memory issue, note that you used or to connect your tables; this actually leads to the fact that almost every record of the involved tables is connected to almost every other record (almost a cross join / cartesian product); This can get very large if you connect 6 tables...
select buq.buq_codigo, tbu.tbu_codigo, tbu.tbu_nombre, pai.pai_codigo, pai.pai_nombre,
pue.pto_codigo, pue.pto_nombre, lin.lin_codigo, lin.lin_nombre, tra.tra_codigo,
tra.tra_nombre, buq.buq_nombre, buq.buq_des, buq.num_trb, buq.num_eslora,
buq.max_tons, buq.reg_lloyd, buq.buq_codigo1, buq.codigo_omi,
case buq.buq_estado when 'A' then 'Activo' else 'Inactivo' end as buq_estado
from publico.mae_buque as buq
left outer join publico.mae_tipbuque as tbu on buq.tbu_codigo = tbu.tbu_codigo
left outer join publico.mae_pais as pai on (buq.pai_codigo = pai.pai_codigo)
left outer join publico.mae_puerto as pue on (buq.pto_codigo = pue.pto_codigo)
left outer join publico.mae_linea as lin on (buq.lin_codigo = lin.lin_codigo)
left outer join publico.mae_trafico as tra on (buq.tra_codigo = tra.tra_codigo)
You have to use left outer join:
select *
from
publico.mae_buque as buq
left outer join publico.mae_tipbuque as tbu on (buq.tbu_codigo = tbu.tbu_codigo)
left outer join publico.mae_pais as pai on (buq.pai_codigo = pai.pai_codigo)
left outer join publico.mae_puerto as pue on (buq.pto_codigo = pue.pto_codigo )
left outer join publico.mae_linea as lin on (buq.lin_codigo = lin.lin_codigo)
left outer join publico.mae_trafico as tra on (buq.tra_codigo = tra.tra_codigo);

LEFT JOIN ON COALESCE(a, b, c) - very strange behavior

I have encountered very strange behavior of my query and I wasted a lot of time to understand what causes it, in vane. So I am asking for your help.
SELECT count(*) FROM main_table
LEFT JOIN front_table ON front_table.pk = main_table.fk_front_table
LEFT JOIN info_table ON info_table.pk = front_table.fk_info_table
LEFT JOIN key_table ON key_table.pk = COALESCE(info_table.fk_key_table, front_table.fk_key_table_1, front_table.fk_key_table_2)
LEFT JOIN side_table ON side_table.fk_front_table = front_table.pk
WHERE side_table.pk = (SELECT MAX(pk) FROM side_table WHERE fk_front_table = front_table.pk)
OR side_table.pk IS NULL
Seems like a simple join query, with coalesce, I've used this technique before(not too many times) and it worked right.
In this query I don't ever get nulls for side_table.pk. If I remove coalesce or just don't use key_table, then the query returns rows with many null side_table.pk, but if I add coalesce join, I can't get those nulls.
It seems key_table and side_table don't have anything in common, but the result is so weird.
Also, when I don't use side_table and WHERE clause, the count(*) result with coalesce and without differs, but I can't see any pattern in rows missing, it seems random!
Real query:
SELECT ECHANGE.EXC_AUTO_KEY, STOCK_RESERVATIONS.STR_AUTO_KEY FROM EXCHANGE
LEFT JOIN WO_BOM ON WO_BOM.WOB_AUTO_KEY = EXCHANGE.WOB_AUTO_KEY
LEFT JOIN VIEW_WO_SUB ON VIEW_WO_SUB.WOO_AUTO_KEY = WO_BOM.WOO_AUTO_KEY
LEFT JOIN STOCK stock3 ON stock3.STM_AUTO_KEY = EXCHANGE.STM_AUTO_KEY
LEFT JOIN STOCK stock2 ON stock2.STM_AUTO_KEY = EXCHANGE.ORIG_STM
LEFT JOIN CONSIGNMENT_CODES con2 ON con2.CNC_AUTO_KEY = stock2.CNC_AUTO_KEY
LEFT JOIN CONSIGNMENT_CODES con3 ON con3.CNC_AUTO_KEY = stock3.CNC_AUTO_KEY
LEFT JOIN CI_UTL ON CI_UTL.CUT_AUTO_KEY = EXCHANGE.CUT_AUTO_KEY
LEFT JOIN PART_CONDITION_CODES pcc2 ON pcc2.PCC_AUTO_KEY = stock2.PCC_AUTO_KEY
LEFT JOIN PART_CONDITION_CODES pcc3 ON pcc3.PCC_AUTO_KEY = stock3.PCC_AUTO_KEY
LEFT JOIN STOCK_RESERVATIONS ON STOCK_RESERVATIONS.STM_AUTO_KEY = stock3.STM_AUTO_KEY
LEFT JOIN WAREHOUSE wh2 ON wh2.WHS_AUTO_KEY = stock2.WHS_ORIGINAL
LEFT JOIN SM_HISTORY ON (SM_HISTORY.STM_AUTO_KEY = EXCHANGE.ORIG_STM AND SM_HISTORY.WOB_REF = EXCHANGE.WOB_AUTO_KEY)
LEFT JOIN RC_DETAIL ON stock3.RCD_AUTO_KEY = RC_DETAIL.RCD_AUTO_KEY
LEFT JOIN RC_HEADER ON RC_HEADER.RCH_AUTO_KEY = RC_DETAIL.RCH_AUTO_KEY
LEFT JOIN WAREHOUSE wh3 ON wh3.WHS_AUTO_KEY = COALESCE(RC_DETAIL.WHS_AUTO_KEY, stock3.WHS_ORIGINAL, stock3.WHS_AUTO_KEY)
WHERE STOCK_RESERVATIONS.STR_AUTO_KEY = (SELECT MAX(STR_AUTO_KEY) FROM STOCK_RESERVATIONS WHERE STM_AUTO_KEY = stock3.STM_AUTO_KEY)
OR STOCK_RESERVATIONS.STR_AUTO_KEY IS NULL
Removing LEFT JOIN WAREHOUSE wh3 gives me about unique EXC_AUTO_KEY values with a lot of NULL STR_AUTO_KEY, while leaving this row removes all NULL STR_AUTO_KEY.
I recreated simple tables with numbers with the same structure and query works without any problems o.0
I have a feeling COALESCE is acting as a REQUIRED flag for the joined table, hence shooting the LEFT JOIN to become an INNER JOIN.
Try this:
SELECT COUNT(*)
FROM main_table
LEFT JOIN front_table ON front_table.pk = main_table.fk_front_table
LEFT JOIN info_table ON info_table.pk = front_table.fk_info_table
LEFT JOIN key_table ON key_table.pk = NVL(info_table.fk_key_table, NVL(front_table.fk_key_table_1, front_table.fk_key_table_2))
LEFT JOIN (SELECT fk_, MAX(pk) as pk FROM side_table GROUP BY fk_) st ON st.fk_ = front_table.pk
NVL might behave just the same though...
I undertood what was the problem (not entirely though): there is a LEFT JOIN VIEW_WO_SUB in original query, 3rd line. It causes this query to act in a weird way.
When I replaced the view with the other table which contained the information I needed, the query started returning right results.
Basically, with this view join, NVL, COALESCE or CASE join with combination of certain arguments did not work along with OR clause in WHERE subquery, all rest was fine. ALthough, I could get the query to work with this view join, by changing the order of joined tables, I had to place table participating in where subquery to the bottom.