Left join same table twice but one column is repeat - sql-server

The main table want to join two time with the reffrence table twice with the same column.
The main table column is insert with integer and need to join with the refference table to get the character back to show back for user.
it show none of records by the sql below, why?
main table BD_BRAND
Sports_BR Leather_BR
2 1
Reffrence table BD_REF
ID NME REF_TYPE
1 NIKE Sports_Brand
2 ADIDAS Sports_Brand
3 PUMA Sports_Brand
1 CLACKS Leather_Brand
2 LOTTUSSE Leather_Brand
3 CHEANEY Leather_Brand
SELECT B.NME AS Sports_BR, C.NME AS Leather_BR
FROM BD_BRAND A
LEFT JOIN BD_REF B on B.ID = A.Sports_BR
LEFT JOIN BD_REF C on C.ID = A.Leather_BR
The Result i want as below:
Sports_BR Leather_BR
ADIDAS CLACKS

I think you're looking for:
SELECT B.NME AS Sports_BR, C.NME AS Leather_BR
FROM BD_BRAND A
LEFT JOIN BD_REF B on B.ID = A.Sports_BR and B.REF_TYPE = 'Sports_Brand'
LEFT JOIN BD_REF C on C.ID = A.Leather_BR and B.REF_TYPE = 'Leather_Brand'
Your ID's are present multiple times due to the different reference types, so you need to specify which ID to grab by the reference type.

Related

Join 4 tables and sum quantity for 2 tables using id from one table

My tables:
Order is:
PurchaseOrderHead
PurchaseOrder
ReceivingNoteHead
ReceivingNote
I want the output like this
MaterialID, PO.Quantity, RN.Quantity so far
There can be multiple receiving notes for a given purchaseorderhead_id as every ReceivingNoteHead will have a PurchaseOrderHeadID.
My attempt:
select
PurchaseOrder.MaterialID,
sum(distinct PurchaseOrder.Quantity) as "Sum_Quantity",
sum(ReceivingNote.Quantity) as "ReceivingNote_Quantity",
PurchaseOrderHead.id
from
(((dbo.PurchaseOrder
inner join
dbo.PurchaseOrderHead on (PurchaseOrderHead.id = PurchaseOrder.PurchaseOrderHeadID))
left outer join
dbo.ReceivingNoteHead ReceivingNoteHead (ReceivingNoteHead.PurchaseOrderHeadID = PurchaseOrderHead.id))
left outer join
dbo.ReceivingNote on (ReceivingNote.ReceivingNoteHeadID = ReceivingNoteHead.id))
group by
PurchaseOrder.MaterialID,
PurchaseOrderHead.id
having
(PurchaseOrderHead.id = 1004)
But ReceivingNote Quantities are repeated when there's no ReceivingNote MaterialID that matches PurchaseOrder's MaterialID.
This also does not work when theres multiple same MaterialID in either PurchaseOrder or ReceivingNote
I would like to learn whether I need to break the ReceivingNote table into 2 tables because of PurchaseOrderHeadID? And I want to get rid of the sum distinct because it's not the way I want it to be.
Maybe by first aggregating the material purchases in a sub-query.
Then left join that to the materials on the receiving end.
Untested notepad scribble:
SELECT
poMat.MaterialID,
poMat.TotQuantity AS [PurchaseOrder_Quantity],
SUM(rn.Quantity) AS [ReceivingNote_Quantity],
poMat.PurchaseOrderHeadID
FROM
(
SELECT
po.PurchaseOrderHeadID,
po.MaterialID,
SUM(po.Quantity) AS TotQuantity
FROM dbo.PurchaseOrder po
-- Uncomment to filter on the PurchaseOrderHeadID
-- WHERE po.PurchaseOrderHeadID = 1004
GROUP BY
po.PurchaseOrderHeadID,
po.MaterialID
) poMat
LEFT JOIN dbo.ReceivingNoteHead rnH
ON rnH.PurchaseOrderHeadID = poMat.PurchaseOrderHeadID
LEFT JOIN dbo.ReceivingNote rn
ON rn.ReceivingNoteHeadID = rnH.id
AND rn.MaterialID = poMat.MaterialID
GROUP BY
poMat.PurchaseOrderHeadID,
poMat.MaterialID,
poMat.TotQuantity
ORDER BY
poMat.PurchaseOrderHeadID,
poMat.MaterialID;
This however, won't show received materials that don't have a matching purchased material.
You are getting duplicate because the table ReceivingNoteHead does not have the PurchaseOrder.ID in it. Add the column PurchaseOrderID in ReceivingNoteHead and you should be good to go
select
PurchaseOrder.MaterialID,
sum(PurchaseOrder.Quantity) as "Sum_Quantity",
sum(ReceivingNote.Quantity) as "ReceivingNote_Quantity",
PurchaseOrderHead.id
from
dbo.PurchaseOrder
inner join
dbo.PurchaseOrderHead on PurchaseOrderHead.id = PurchaseOrder.PurchaseOrderHeadID
left outer join
dbo.ReceivingNoteHead ReceivingNoteHead ReceivingNoteHead.PurchaseOrderHeadID = PurchaseOrderHead.id *and ReceivingNoteHead.PurchaseOrderID=PurchaseOrder.ID*
left outer join
dbo.ReceivingNote on ReceivingNote.ReceivingNoteHeadID = ReceivingNoteHead.id
group by
PurchaseOrder.MaterialID,
PurchaseOrderHead.id
having
PurchaseOrderHead.id = 1004

sql server - How to Get all distinct value in group by column from two table and count from another table for each value

I have 3 tables in that 2 tables are master table and 3rd is transaction table. i need to get count from transaction table for each value in other two table without loosing rows in mater table
i need result like below
Table layout for understanding
This is the code i have tried,
select s.status_name, e.machine_group_name, qty = COALESCE(COUNT(e.id),0)
from tbl_status s
left outer JOIN tbl_transaction as e ON e.status_name = s.status_name
group by e.machine_group_name, s.status_name
This is solution i have figured:
select m.machine_group_name, s.status_name, qty = COUNT(e.id) from
tbl_machine_group as m
cross join tbl_status as s
left outer join tbl_transaction as e on e.status_name = s.status_name
and e.machine_group_name = m.machine_group_name
group by m.machine_group_name, s.status_name
order by machine_group_name
select
MC_Group_Name
,Status_Name
,count(1) as [Count of Transaction]
from
tbl_Transaction tbl_3
left join tbl_Machine_Group tbl_1
on tbl_3.MC_Group_Name = tbl_1.MC_Group_Name
left join tbl_Status tbl_2
on tbl_3.Status_Name = tbl_2.Status_Name
group by
MC_Group_Name
,Status_Name

SQL - Multi Table Joining with 1-1 and 1 - Many relationship

I am trying to learn SQL and want to understand a scenario where i can Join 2 separate queries.
I have my APP_MTRX table would join with Cust Table to retrieve all the records whose TYPE_ORD_NUM = 0 or 1
I need to join ADD_DTLS Table with SHR_ADR table based on SHR_ADR_ID and need to retrieve all the columns whose adr_type_id is either 0 or 1 again
joining the result of 1 and 2
below is my SQL
select * from app_mtrx ABC
left join cust on cust.cust_id = ABC.cust_id and abc.cust_ty_ord = 0
left join cust BBC on cust.cust_id = BBC.cust_id and abc.cust_ty_ord = 1
left join add_dtls DEF ON DEF.cust_id=BBC.cust_id
left join shr_adr SHR on shr.shr_adr_id = def.shr_Adr_id
Can you please suggest if this is the correct approach and also if it is joining my 1 & 2 correctly....
Try this:
SELECT * FROM APP_MTRX am INNER JOIN Cust c
ON am.cust_id = c.cust_id
AND am.cust_ty_ord in (0,1)
INNER JOIN add_dtls ad
ON ad.cust_id=c.cust_id
INNER JOIN shr_adr sh
ON ad.shr_adr_id = sh.shr_Adr_id
AND ad.adr_type_id in (0,1)

Concatenate fields and join tables using iReports

I'm trying to concatenate two fields in one table and another two fields in another table and using the concatenated value as the primary key to join the tables together.
Due to the fact that the primary key is linked to example 5 different people i need a unique value per person concatenating a policy number with a dep code.
The following is an example of how to run the query with MSSQL (I did not include the full code - just an example).
Alter table [beneficiary] add [Unique] varchar(max)
Update [beneficiary] Set [Unique] =concat([t1.ms_fk],[t1.dep_fk])
Alter table [tsf_claim] add [Unique] varchar(max)
Update [tsf_claim] Set [Unique1] =concat([t5.ms_fk],[t5.dep_fk])
LEFT JOIN [mipbi_dbo.td_beneficiary] t5 ON t1.[Unique] = t5.[Unique1]
I need to include the above in iReports as the final left join and I dont know how to create additional field in iReports. Also note that my iReports is a very old version (3.7.1)
SELECT t1.scheme_fk,t1.ms_fk,t1.dep_fk,t1.pr_fk,t1.tariff_fk,t1.icd10_fk,t1.claimed_amount,t1.benefit_amount,t1.auth_fk,t1.units,t1.paid_date,
t1.claim_date,t1.claim_code,t1.ref_pr_fk,t1.note,t1.cheque_datetime,t1.suspend_until,t1.dr_mem,t1.suspended,
t2.mem_num,t2.xref_num,
t3.icd10_pk,t3.icd10_descr,
t4.claim_code,t4.description,
t5.initials,t5.surname,
FROM mipst_dbo.tsf_claim as t1
LEFT JOIN mipst_dbo.tsf_memxref t2 ON t1. ms_fk = t2.mem_num
LEFT JOIN mipbi_dbo.td_icd10 t3 ON t1.icd10_fk = t3.icd10_pk
LEFT JOIN mipst_dbo.tsd_ccdesc t4 ON t1.claim_code = t4.claim_code::integer
LEFT JOIN mipbi_dbo.td_beneficiary t5 ON t1.ms_fk = t5.ms_pk
WHERE t1.scheme_fk = '75'
GROUP BY t1.scheme_fk,t1.ms_fk,t1.dep_fk,t1.pr_fk,t1.tariff_fk,t1.icd10_fk,t1.claimed_amount,t1.benefit_amount,t1.auth_fk,t1.units,t1.paid_date,
t1.claim_date,t1.claim_code,t1.ref_pr_fk,t1.note,t1.cheque_datetime,t1.suspend_until,t1.dr_mem,t1.suspended,
t2.mem_num,t2.xref_num,
t3.icd10_pk,t3.icd10_descr,
t4.claim_code,t4.description,
t5.initials,t5.surname
By adding the left join 'LEFT JOIN mipbi_dbo.td_beneficiary t5 ON t1.ms_fk = t5.ms_pk' it is not adding the persons name according to the dependant code. It is merely just joining the lines.
In short a policy number is linked to different people with a dependent code, so when joining the information dep 1 should be linked to dep 1 from the second table with the correct name and surname etc.
In table 1 dep 1 can have say 10 lines, so with the current code it is adding all the information for the policy number on the 10 lines and not just the information for dep 1.
Let me know if the above is clearly defined or if you need more information.
I was able to resolve the query by merely
SELECT t1.scheme_fk,t1.ms_fk,t1.dep_fk,t1.pr_fk,t1.tariff_fk,t1.icd10_fk,t1.claimed_amount,t1.benefit_amount,t1.auth_fk,t1.units,t1.paid_date,
t1.claim_date,t1.claim_code,t1.ref_pr_fk,t1.note,t1.cheque_datetime,t1.suspend_until,t1.dr_mem,t1.suspended,
t2.mem_num,t2.xref_num,
t3.icd10_pk,t3.icd10_descr,
t4.claim_code,t4.description,t4.scheme_code,
t5.ms_pk,t5.dep_fk,t5.initials,t5.surname,
t6.narration,t6.key
FROM mipst_dbo.tsf_claim as t1
LEFT JOIN mipst_dbo.tsf_memxref t2 ON t1. ms_fk = t2.mem_num
LEFT JOIN mipbi_dbo.td_icd10 t3 ON t1.icd10_fk = t3.icd10_pk
LEFT JOIN mipst_dbo.tsd_ccdesc t4 ON t1.claim_code = t4.claim_code::integer
LEFT JOIN mipbi_dbo.td_beneficiary t5 ON t1.ms_fk = t5.ms_pk
LEFT JOIN mipst_dbo.tsf_note t6 ON t1.note = t6.key
WHERE t1.scheme_fk = '28' and
t4.scheme_code = '28' and
t1.ms_fk = t5.ms_pk AND
t1.dep_fk =t5.dep_fk
GROUP BY t1.scheme_fk,t1.ms_fk,t1.dep_fk,t1.pr_fk,t1.tariff_fk,t1.icd10_fk,t1.claimed_amount,t1.benefit_amount,t1.auth_fk,t1.units,t1.paid_date,
t1.claim_date,t1.claim_code,t1.ref_pr_fk,t1.note,t1.cheque_datetime,t1.suspend_until,t1.dr_mem,t1.suspended,
t2.mem_num,t2.xref_num,
t3.icd10_pk,t3.icd10_descr,
t4.claim_code,t4.description,t4.scheme_code,
t5.ms_pk,t5.dep_fk,t5.initials,t5.surname,
t6.narration,t6.key
updating the where clause.

SQL Select random from multiple table and order by specific criteria on one table

I need to select a random record from 3 tables and ensure I am ordering by photoOrder
Select TOP 1(a.id), a.mls_number, a.parcel_name, a.property_type, a.ownership_type, b.filename, b.photoOrder, c.county_Name
From property as a
Inner JOIN
listingPhotos as b on a.id = b.ListingID
LEFT JOIN
counties as C on a.county_name = c.id
WHERE a.isCommercial = 'True'
Order By NEWID()
So this query works, but I need to ensure that the b.filename record is ordered by b.photoOrder and thus the b.photoOrder should always be 1.
The b table (listing photos) has multiple photo files per property and I need to only select the photo that is 1st in the photo order.
Thanks
You could subquery your listingPhotos table and limit to WHERE PhotoOrder = 1:
Select TOP 1(a.id), a.mls_number, a.parcel_name, a.property_type, a.ownership_type, b.filename, b.photoOrder, c.county_Name
From property as a
Inner JOIN
(SELECT ListingID , filename, PhotoOrder FROM listingPhotos WHERE PhotoORder = 1
) as b on a.id = b.ListingID
LEFT JOIN
counties as C on a.county_name = c.id
WHERE a.isCommercial = 'True'
Order By NEWID()

Resources