LEFT OUTER JOIN WITH inner join with case in SQL DBMS - sql

I have the following query
SELECT
A.WORKNR AS "WORK-nr",
UCASE(A.NAME) AS "NAME" ,
UCASE(A.ADRESS) AS "adress",
A.ZIPNR,
UCASE(A.ZIPADR) AS "zipadress",
A.NNR,
CASE
WHEN AO.ORG_REF IS NULL THEN 'OK'
ELSE 'NO '
END AS RESULT OF ORG ,
CASE
WHEN B.B = 1 THEN 'OK'
ELSE 'COME WITH ANOTHER NNR'
END AS COMPARE_RESULT
FROM
WORK.WORK_ADRESS A
LEFT JOIN
(SELECT
POSTNR, UCASE(STREET) AS STREET,
COUNT(DISTINCT NNR) AS B
FROM
WORK.WORK_ADRESS
GROUP BY
ZIPNR, UCASE(STREET)) B ON B.STREET = UCASE(A.STREET)
AND B.ZIPNR = ZIPNR
LEFT JOIN
(SELECT *
FROM WORK.ORGANISATION2) AO ON AO.WORK_REF = A.WORK_REF
AND AO.TILL >= CURRENT DATE
what I want is to add a JOIN to a third table ORG3 that contains the name for org genom
SELECT WORK.ORGANISATION2
INNER JOIN STYR.ORG2 ORG3 ON AO.ORG_REF3 = ORG3.ORG_REF
and get the column OR3.NAME as a separate column.
Can anyone help me? I am thankful

Related

SQL server Select Distinct with Order By

I am not very known to DB query but getting error
"ORDER BY items must appear in the select list if SELECT DISTINCT is
specified."
with below query. I searched on google and found that order by need to group if using Distinct but still not able to get it. Can anyone help me out.
SELECT DISTINCT
P1.*
FROM T_PRD P1
LEFT JOIN T_PRD P2 ON P1.baseprdid = P2.prdid
INNER JOIN T_PRD_NM_VENDOR prdNmVendor ON P1.prdId = prdNmVendor.prdId
INNER JOIN T_VENDOR_NM vendorNM ON prdNmVendor.vendorNMId = vendorNM.vendorNMId
INNER JOIN T_NM nm ON vendorNM.NMId = nm.NMId
INNER JOIN T_PRD_VENDOR prdVendor ON prdVendor.PRDId = P1.PRDId
INNER JOIN T_VENDOR vendor ON prdVendor.vendorId = vendor.vendorId
INNER JOIN T_CSTMR_PRD_REF custPrd ON custPrd.ProductId = P1.PRDId
INNER JOIN T_CSTMR cstmr ON custPrd.ChennelCstrId = cstmr.cstmrid
WHERE 1 = 1
AND P1.Lifecycle = 2
AND P1.AutoCreated = 0
AND vendor.vendorId = 1
AND P1.VendorEnfId = 1
AND cstmr.cstmrid = 2008
ORDER BY CASE
WHEN P1.BASEPRDID = 0
THEN P1.PRDNAME
ELSE P2.PRDNAME
END ASC,
BASEPRDID;
Your ORDER BY depends on expression which is missing from SELECT DISTINCT list . Add it
SELECT DISTINCT P1.*
,CASE
WHEN P1.BASEPRDID = 0
THEN P1.PRDNAME
ELSE P2.PRDNAME
END col

Select an ID where there is only one row and that row is a specific value

I have this query. There's a lot of joins because I am checking if an ID is linked to any of those tables.
Currently, this query shows me any ID's that are not linked to any of those tables. I would like to add to it so that it also shows any IDs that are linked to the d table, but only if there is only 1 row in the D table and the type in the D field is 'member'.
SELECT
c.ID,
c.location,
c.pb,
c.name,
c.surname
FROM c
LEFT JOIN l on c.rowno = l.rowno
LEFT JOIN d on c.rowno = d.rowno
LEFT JOIN t on c.rowno = t.rowno
LEFT JOIN cj ON (c.rowno = cj.rowno OR c.rowno = cj.rowno2)
LEFT JOIN dj ON c.rowno = d.rowno
LEFT JOIN lg ON c.rowno = lg.rowno
LEFT JOIN tj ON c.rowno = tj.rowno
WHERE
c.status != 'closed'
AND l.rowno IS NULL
AND d.rowno IS NULL
AND t.rowno IS NULL
AND cj.rowno IS NULL
AND dj.rowno IS NULL
AND lg.rowno IS NULL
AND tj.rowno IS NULL
My first thought is to just add
WHERE D.type = 'member'
But that gives me all IDs that have a row with D.type = member (they could have 10 rows with all different types, but as long as 1 of those has type = member it shows up). I want to see ID's that ONLY have d.type = member
I'm sorry if I'm wording this badly, I'm having trouble getting this straight in my head. Any help is appreciated!
I would use exists for all conditions except the one on the D table:
SELECT c.*
FROM c JOIN
(SELECT d.rownum, COUNT(*) as cnt,
SUM(CASE WHEN d.type = 'Member' THEN 1 ELSE 0 END) as num_members
FROM t
GROUP BY d.rownum
) d
ON c.rownum = d.rownum
WHERE c.status <> 'closed' AND
NOT EXISTS (SELECT 1 FROM t WHERE c.rowno = t.rowno) AND
NOT EXISTS (SELECT 1 FROM l WHERE c.rowno = l.rowno) AND
. . .
I find NOT EXISTS is easier to follow logically. I don't think there is a big performance difference between the two methods in SQL Server.

SQL server Left join with child tables and get the table name

Let's assume we have a table Instrument with child tables Equity and Bond having a foreign key InstrumentId. Each instrument has a unique record in one of the child tables.
Is it possible to make a view using left joins to see all the instrument with a column containing the table name in which the record is present ?
SELECT Instrument.InstrumentId, Instrument.Name, ***CHILD_TABLE_NAME***
FROM Instrument
LEFT OUTER JOIN
Equity ON Equity.InstrumentId = Instrument.InstrumentId
LEFT OUTER JOIN
Bond ON SBond.InstrumentId = Instrument.InstrumentId
An alternative is to make an union of inner joins:
SELECT instrumentId, Name, instrumentType
FROM
(SELECT Instrument.instrumentId, Name, 'Equity' as instrumentType FROM dbo.Equity inner join Instrument on Instrument.InstrumentId = Equity.InstrumentId
UNION
SELECT Instrument.instrumentId, Name, 'Bond' as instrumentType from dbo.Bond inner join Instrument on Instrument.InstrumentId = Bond.InstrumentId) u
one option is to include the table name in your joins like this
SELECT i.InstrumentId,
i.Name,
e.TableEquity,
b.TableBond
FROM Instrument i
LEFT OUTER JOIN (select 'Equity' as TableEquity from Equity) e
ON i.InstrumentId = e.InstrumentId
LEFT OUTER JOIN (select 'Bond' as TableBond from Bond) b
ON i.InstrumentId = b.InstrumentId
EDIT by #sofsntp : to merge the Equity/Bond in one column
SELECT i.InstrumentId,
i.Name,
(ISNULL(e.TableEquity,'') + ISNULL(b.TableBond ,''))
FROM Instrument i
LEFT OUTER JOIN (select *, 'Equity' as TableEquity from Equity) e
ON e.InstrumentId = i.InstrumentId
LEFT OUTER JOIN (select *, 'Bond' as TableBond from StraightBond) b
ON b.InstrumentId = i.InstrumentId
Use a case expression:
SELECT i.InstrumentId, i.Name,
(CASE WHEN e.InstrumentId IS NOT NULL THEN 'Equity'
WHEN b.InstrumentId IS NOT NULL THEN 'Bond'
END) as which_table
FROM Instrument i LEFT OUTER JOIN
Equity e
ON e.InstrumentId = i.InstrumentId LEFT OUTER JOIN
Bond b
ON b.InstrumentId = i.InstrumentId ;
Note: This gives the first match. If you want both:
SELECT i.InstrumentId, i.Name,
((CASE WHEN e.InstrumentId IS NOT NULL THEN 'Equity' ELSE '' END) +
(CASE WHEN b.InstrumentId IS NOT NULL THEN 'Bond' ELSE '' END)
) as which_table
FROM Instrument i LEFT OUTER JOIN
Equity e
ON e.InstrumentId = i.InstrumentId LEFT OUTER JOIN
Bond b
ON b.InstrumentId = i.InstrumentId ;
EDIT
I am adding END which was missing

Excluding rows derived from case statement with a specific value based on values from another column

How do I exclude rows with a specific value in a field based on specific values of another field? To dive deeper:
I have a column called "rule_name" that's derived from a case statement.
I have another column called "DeliveryTermsIdentifier" that's pulled from another table (see image of query result below).
I'm trying to remove rows with rule_name "Delivery event required" only if DeliveryTermsIdentifier is "PP", "DA", ect. I'm getting thrown off because my rule_name column is based off a condition already.
image of query result
Here is the SQL used to derive those 2 columns:
,case when s.ShipmentNo is not null then cast(dqr.rulename as varchar(30))
else cast(dqc.dataqualityruleid as varchar(30)) end as rule_name
,case when (dqd.SuccessFlag = 0) then 'Missing'
when (dqd.SuccessFlag = 1) then 'Reported'
when (s.ShipmentNo is null) then 'Missing' end reporting_result
,s.DeliveryTermsIdentifier
from CustomerMasterList cml
join organization o on o.organizationid = cml.senderid
inner join DataQualityConfig dqc on dqc.DomainId = cml.DomainID
left outer join shipment s on s.shipmentno = cml.shipmentno
left outer join dataqualityresult dqd on dqd.shipmentid = s.shipmentid
left outer join dataqualityrule dqr on dqr.dataqualityruleid
=dqd.dataqualityruleid
One way is to put what you have in a subquery and filter out with a where clause in the outer query. E.g.
SELECT rule_name, reporting_result, DeliveryTermsIdentifier
FROM
(SELECT 'X'
,case when s.ShipmentNo is not null then cast(dqr.rulename as varchar(30))
else cast(dqc.dataqualityruleid as varchar(30)) end as rule_name
,case when (dqd.SuccessFlag = 0) then 'Missing'
when (dqd.SuccessFlag = 1) then 'Reported'
when (s.ShipmentNo is null) then 'Missing' end reporting_result
,s.DeliveryTermsIdentifier
from CustomerMasterList cml
join organization o on o.organizationid = cml.senderid
inner join DataQualityConfig dqc on dqc.DomainId = cml.DomainID
left outer join shipment s on s.shipmentno = cml.shipmentno
left outer join dataqualityresult dqd on dqd.shipmentid = s.shipmentid
left outer join dataqualityrule dqr on dqr.dataqualityruleid
=dqd.dataqualityruleid ) AS sub
WHERE DeliveryTermsIdentifier NOT IN ('PP', 'DA') AND rule_name <> 'Delivery event required'
You can also encapsulate your case statements into an outer apply and use the alias like this:
SELECT * ,
rules.rule_name ,
RESULT.reporting_result ,
s.DeliveryTermsIdentifier
FROM CustomerMasterList cml
JOIN organization o ON o.organizationid = cml.senderid
INNER JOIN DataQualityConfig dqc ON dqc.DomainId = cml.DomainID
LEFT OUTER JOIN shipment s ON s.shipmentno = cml.shipmentno
LEFT OUTER JOIN dataqualityresult dqd ON dqd.shipmentid = s.shipmentid
LEFT OUTER JOIN dataqualityrule dqr ON dqr.dataqualityruleid = dqd.dataqualityruleid
OUTER APPLY ( SELECT CASE WHEN ( dqd.SuccessFlag = 0 ) THEN 'Missing'
WHEN ( dqd.SuccessFlag = 1 ) THEN 'Reported'
WHEN ( s.ShipmentNo IS NULL ) THEN 'Missing'
END reporting_result ) RESULT
OUTER APPLY ( SELECT CASE WHEN s.ShipmentNo IS NOT NULL THEN
CAST(dqr.rulename AS VARCHAR(30))
ELSE
CAST(dqc.dataqualityruleid AS VARCHAR(30))
END AS rule_name ) rules
WHERE s.DeliveryTermsIdentifier NOT IN ( 'PP', 'DA' )
AND rules.rule_name <> 'Delivery event required';

Conditional Inner Join

I want to be able to inner join two tables based on the result of an expression.
What I've been trying so far:
INNER JOIN CASE WHEN RegT.Type = 1 THEN TimeRegistration ELSE DrivingRegistration AS RReg
ON
RReg.RegistreringsId = R.Id
RegT is a join I made just before this join:
INNER JOIN RegistrationTypes AS RegT ON R.RegistrationTypeId = RegT.Id
This SQL-script does not work.
So all in all, if the Type is 1, then it should join on the table TimeRegistration else it should join on DrivingRegistration.
Solution:
In my select statement I performed the following joins:
INNER JOIN RegistrationTypes AS RegT ON R.RegistrationTypeId = RegT.Id
LEFT OUTER JOIN TimeRegistration AS TReg ON TReg.RegistreringsId = R.Id AND RegT.Type = 1
LEFT OUTER JOIN DrivingRegistration AS DReg ON DReg.RegistreringsId = R.Id AND RegT.Type <>1
Then I edited my where-clause to output the correct, depending on the RegType, like this:
WHERE (CASE RegT.Type WHEN 1 THEN TReg.RegistreringsId ELSE DReg.RegistreringsId END = R.Id)
Try putting both tables in the query using LEFT JOIN's
LEFT JOIN TimeRegistration TR ON r.rid = TR.Id AND RegT.type =1
LEFT JOIN DrivingRegistration DR ON r.rid = DR.Id AND RegT.type <>1
Now, in you select clause, use
CASE RegType.Type WHEN 1 THEN TR.SomeField ELSE DR.someField END as SomeField
The other option is to use dynamic SQL
You probably need to perform two left joins, one onto TimeRegistration and one onto DrivingRegistration, and return the fields you want from the appropriate join table something like this:
LEFT JOIN TimeRegistration ON TimeRegistration.RegistreringsId = R.Id
LEFT JOIN DrivingRegistration ON DrivingRegistration.RegistreringsId = R.Id
and you select statement would be something like this:
SELECT CASE WHEN RegT.Type = 1 THEN TimeRegistration.Foo ELSE DrivingRegistration.Bar END
I like what you're trying to do, but I don't think SQL is that clever.
SELECT
R.foo, tr.bar
FROM
SomeTable AS R
INNER JOIN RegistrationTypes AS RegT ON R.RegistrationTypeId = RegT.Id
AND RegT1.Type = 1
INNER JOIN TimeRegistration AS tr ON /* whatever */
UNION
SELECT
R.foo, dr.bar
FROM
SomeTable AS R
INNER JOIN RegistrationTypes AS RegT ON R.RegistrationTypeId = RegT.Id
AND RegT1.Type = 2
INNER JOIN DrivingRegistration AS dr ON /* whatever */
So I had a scenario where there were three email columns in one table (don't ask why) and any of them could be null (or empty). In this example code I will just deal with a case where it is null.
I had to join it to another table by any of the emails to retrieve the users firstname.
Here is what worked
select
m.email1,
m.email2,
m.email3,
m2.firstName
from MyTable m
left join MyOtherTable m2 on m2.Email =
case when m.email1 is null then
case when m.email2 is null then
case when m.email3 null then
'nonexistent#mydomain.com' -- i stopped here
else m.email3 end
else wm.email2 end
else m.email1 end
Obviously you would include further conditions like
case when m.email1 is null or m.email1 = '' then ...
To cover for empty values.