Merge data when inserting into another table with the same ID - sql-server

I have a table with the following data, the lab_sample_id are identical, I’m inserting this data into another table. I would like to merge the data when inserting into another table if the lab_sample_id is the same for leg_id 1 and 3.
leg_id 1 & 3 will always have unique data but the lab_sample_id might be identical.
Here's my current code:
INSERT INTO SAMPLE_RESULT
(PPK, LAB_SAMPLE_ID, LEG_ID, PT, PT_METHOD,
PT_MIN_DETECTION, CU, CU_METHOD, CU_MIN_DETECTION)
SELECT B.PK, CSR.LAB_SAMPLE_ID, CSR.LEG_ID, CSR.PT, CSR.PT_METHOD,
CSR.PT_MIN_DETECTION, CSR.CU, CSR.CU_METHOD, CSR.CU_MIN_DETECTION
FROM [SOURCE] S
JOIN CLEARING_BATCH CB ON CB.PPK = S.PK
JOIN CLEARING_SAMPLE_RESULT CSR ON CSR.PPK = CB.PK
JOIN SAMPLE_REG SR ON SR.FIELD_SAMP_ID = CSR.LAB_SAMPLE_ID
LEFT JOIN PROSPECTS_AND_MINES PM ON PM.PPK = S.PK
LEFT JOIN LABORATORY L ON L.PPK = PM.PK
LEFT JOIN BATCH B ON L.PK = B.PPK
WHERE CB.PK =#Submission_Pk
AND CB.BATCH_ID = B.BATCH_ID
AND NOT EXISTS(SELECT *
FROM SAMPLE_RESULT SR
WHERE SR.PPK = B.PK
AND SR.LAB_SAMPLE_ID = CSR.LAB_SAMPLE_ID
AND SR.LEG_ID = CSR.LEG_ID)

Something like this should do the trick, where you can JOIN the table to itself:
SELECT t1.LAB_SAMPLE_ID,
t1.LEG_ID,
t1.PT,
t1.PT_METHOD,
t1.PT_MIN_DETECTION,
t2.cu,
t2.CU_METHOD,
t2.CU_MIN_DETECTION
FROM CLEARING_SAMPLE_RESULT t1
INNER JOIN CLEARING_SAMPLE_RESULT t2
ON t1.LAB_SAMPLE_ID = t2.LAB_SAMPLE_ID
WHERE t1.LAB_SAMPLE_ID = 1 AND t2.LAB_SAMPLE_ID = 3
Then you can modify your UPDATE logic to use this data.

Related

Filter a table using COUNT SQL Server

I am new to SQL. I have written the code below but am getting stuck with the COUNT function. I want to only display the ClientIDs that have 2 or more ServiceIDs on the Service table. I tried doing a nested select within the join on the Service table originally and was getting error messages. Now with the code below, I am getting an error
Msg 164, Level 15, State 1, Line 13
Each GROUP BY expression must contain at least one column that is not an outer reference.
I am trying to achieve the following. THANK YOU!
client Id
Service ID
Count
1
2
3
1
3
3
1
4
3
2
5
4
2
6
4
2
7
4
2
8
4
SELECT DISTINCT
O.OrgName,
Referral.ClientID,
Client.FirstName,
Client.LastName,
P.ProviderName AS 'School',
E.ProgramID,
LI.ListLabel AS 'Reason',
Race.ListLabel AS 'Race/Ethnicity',
Gender.ListLabel AS 'Sex/Gender',
[ServiceId],
(SELECT COUNT([ServiceID])
GROUP BY Referral.ClientID
HAVING COUNT([ServiceID]) >= 2) AS 'Number of Supports'
FROM
ProviderReferral Referral
JOIN
Provider P ON ReferFromProviderID = P.EntityID
JOIN
ProviderReferralExt ON Referral.ProviderReferralID = ProviderReferralExt.ProviderReferralID
INNER JOIN
MultiSelectValue MSV ON MSV.ContextID = Referral.ProviderReferralID
AND MSV.ContextTypeID = 87
AND MSV.ListID = 1000001179
INNER JOIN
Client ON Referral.ClientID = Client.EntityID
INNER JOIN
EnrollmentMember ON client.EntityID = EnrollmentMember.ClientID
INNER JOIN
Enrollment E ON EnrollmentMember.EnrollmentID = E.EnrollmentID
AND E.X_CMNonCM = 1
INNER JOIN
ListItem LI ON LI.ListValue = MSV.ListValue
AND LI.ListID = 1000001179
INNER JOIN
ListItem Race ON Race.ListValue = client.Race
AND Race.ListID = 1000000068
INNER JOIN
ListItem Gender ON Gender.ListValue = Client.Gender
AND Gender.ListID = 1
INNER JOIN
Service ON E.EnrollmentID = Service.EnrollmentID -- the supports table
JOIN
Organization O ON o.EntityID = p.OrganizationID
WHERE
P.OrganizationID = 33847
AND E.ProgramID = 1325
AND referral.DeletedDate = '9999-12-31'
AND o.DeletedDate = '9999-12-31'
AND enrollmentmember.DeletedDate = '9999-12-31'
ORDER BY
referral.ClientID, client.FirstName
You can use window function count as follows:
Select * from
(Select ...
...
Count([ServiceID]) over (partition by referral.clientid) as cnt
From ...
...
) t where cnt > 2;
Please note order by should be last clause in your query. Use it accordingly.
Based on the request in the comment, Adding the code into your original query as follows:
select * from
(select Referral.ClientID,
Client.FirstName,
Client.LastName,
P.ProviderName as School,
E.ProgramID,
LI.ListLabel as Reason,
Race.ListLabel as "Race/Ethnicity",
Gender.ListLabel as "Sex/Gender",
[ServiceId],
Count([ServiceID]) over (partition by referral.clientid) as cnt -- this -- added open parenthesis before partition
FROM ProviderReferral Referral
JOIN Provider P on ReferFromProviderID=P.EntityID
JOIN ProviderReferralExt on Referral.ProviderReferralID=ProviderReferralExt.ProviderReferralID
INNER JOIN MultiSelectValue MSV on MSV.ContextID = Referral.ProviderReferralID AND
MSV.ContextTypeID=87 AND MSV.ListID=1000001179
INNER JOIN Client on Referral.ClientID=Client.EntityID
INNER JOIN EnrollmentMember on client.EntityID=EnrollmentMember.ClientID
INNER JOIN Enrollment E on EnrollmentMember.EnrollmentID=E.EnrollmentID and E.X_CMNonCM=1
INNER JOIN ListItem LI on LI.ListValue = MSV.ListValue and LI.ListID = 1000001179
INNER JOIN ListItem Race on Race.ListValue=client.Race and Race.ListID=1000000068
INNER JOIN ListItem Gender on Gender.ListValue=Client.Gender and Gender.ListID=1
INNER JOIN Service on E.EnrollmentID=Service.EnrollmentID -- the supports table
JOIN Organization O on o.EntityID =p.OrganizationID
Where P.OrganizationID=33847
and E.ProgramID=1325
and referral.DeletedDate = '9999-12-31' and o.DeletedDate='9999-12-31'
and enrollmentmember.DeletedDate='9999-12-31') t
where cnt > 2 -- this
order by ClientID, FirstName

Update does not add the correct values

My select statement returns the ids from the tables I have joined correctly(393, starting at 92 and going up 484, its not a PK field, so some ids can be used more then once) there is a total of 550 rows I need to update, when I run the update it only adds the number 92 to the table for all 550 rows.
update movements set [location] = locaID.id FROM (
SELECT
lo.id
FROM [Harvest_Transactions] ht
left join [Harvest_Master_Shift] hms on ht.Harvest_Master_id = hms.Harvest_Master_id
left join [Greenhouse_Troughs] gt on ht.Trough = gt.Greenhouse_Trough_id
left join [batches] b on b.name = hms.Batch_id
left join [phases] p on p.batch = b.id and p.[type] = 3
left join #loc lo on lo.name = gt.Trough_No and lo.area = gt.SQM_per_Trough and lo.Bay_id = gt.Bay_id
where ht.Number_of_Plants_Harvested != 0 and (hms.CreatedOn <= '2020-02-05 09:33:00.000' OR hms.CreatedOn is null )
)locaID where product = 14
what am I missing so it updates with the correct values?
My first impression of your query is that only the rows with product = 14 in movements table will be updated with the single value coming from the subquery.
If you want to update the values based on another derived table, you need some way to link the rows together - i.e a JOIN between your table being updated and the table that holds the other data (see here )
What is the common column between movements and
SELECT
lo.id
FROM [Harvest_Transactions] ht
left join [Harvest_Master_Shift] hms on ht.Harvest_Master_id = hms.Harvest_Master_id
left join [Greenhouse_Troughs] gt on ht.Trough = gt.Greenhouse_Trough_id
left join [batches] b on b.name = hms.Batch_id
left join [phases] p on p.batch = b.id and p.[type] = 3
left join #loc lo on lo.name = gt.Trough_No and lo.area = gt.SQM_per_Trough and
lo.Bay_id = gt.Bay_id
where ht.Number_of_Plants_Harvested != 0 and (hms.CreatedOn <= '2020-02-05
09:33:00.000' OR hms.CreatedOn is null )
The rough syntax shouldI think be
UPDATE movements
set [location] = locaID.id
FROM movements
JOIN (
SELECT
lo.id
FROM [Harvest_Transactions] ht
left join [Harvest_Master_Shift] hms on ht.Harvest_Master_id = hms.Harvest_Master_id
left join [Greenhouse_Troughs] gt on ht.Trough = gt.Greenhouse_Trough_id
left join [batches] b on b.name = hms.Batch_id
left join [phases] p on p.batch = b.id and p.[type] = 3
left join #loc lo on lo.name = gt.Trough_No and lo.area = gt.SQM_per_Trough and
lo.Bay_id = gt.Bay_id
where ht.Number_of_Plants_Harvested != 0 and (hms.CreatedOn <= '2020-02-05
09:33:00.000' OR hms.CreatedOn is null )
) locaID
ON movements.<some column> = locaID.<some column>

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)

inner join multiple tables with multiple columns in linq query not works

I have met the following problems when I use join of multiple tables with multiple columns, I will encounter the error message "The type arguments cannot be inferred from the query." around the "join T4".
In simple SQL world, the following SQL query is normal, and can be executed well.
select A.AColumn1, B.BColumn from TableA A
inner join TableB B
ON A.AColumn1 = B.BColumn1 AND A.AColumn2 = B.BColumn2
inner join TableC C
ON A.AColumn1 = C.CColumn1 AND A.AColumn2 = C.CColumn2
inner join TableD d
But when there are three tables, and all the 2 inner join conditions are related to two or more Columns, I got the trouble.
Linq SQL Example:
var query = from A in TableA
join B from TableB
on new {Column1 = A.AColunm1, Column2 = A.AColunm2} equals
new {Column1 = B.BColunm1, Column2 = B.BColunm2}
join C from TableC
on new {Column1 = A.AColunm1, Column2 = B.BColunm2} equals
new {Column1 = C.CColunm1, Column2 = C.CColunm2}
select new {A.AColunm1, C.CColunm2};
The error will happen at the join C

JOIN codition in SQL Server

After applying join condition on two tables I want records which is maximum among records of left table
My query
SELECT a1.*,
t.*,
( a1.trnratefrom - t.trnratefrom )AS minrate,
( a1.trnrateto - t.trnrateto ) AS maxrate
FROM (SELECT a.srno,
trndate,
b.trnsrno,
Upper(Rtrim(Ltrim(b.trnstate))) AS trnstate,
Upper(Rtrim(Ltrim(b.trnarea))) AS trnarea,
Upper(Rtrim(Ltrim(b.trnquality))) AS trnquality,
Upper(Rtrim(Ltrim(b.trnlength))) AS trnlength,
Upper(Rtrim(Ltrim(b.trnunit))) AS trnunit,
b.trnratefrom,
b.trnrateto,
a.remark,
entdate
FROM mstprodrates a
INNER JOIN trnprodrates b
ON a.srno = b.srno)a1
INNER JOIN (SELECT c.srno,
trndate,
d.trnsrno,
Upper(Rtrim(Ltrim(d.trnstate))) AS trnstate,
Upper(Rtrim(Ltrim(d.trnarea))) AS trnarea,
Upper(Rtrim(Ltrim(d.trnquality))) AS trnquality,
Upper(Rtrim(Ltrim(d.trnlength))) AS trnlength,
Upper(Rtrim(Ltrim(d.trnunit))) AS trnunit,
d.trnratefrom,
d.trnrateto,
c.remark,
entdate
FROM mstprodrates c
INNER JOIN trnprodrates d
ON c.srno = d.srno) AS t
ON a1.trnstate = t.trnstate
AND a1.trnquality = t.trnquality
AND a1.trnunit = t.trnunit
AND a1.trnlength = t.trnlength
AND a1.trnarea = t.trnarea
AND a1.remark = t.remark
WHERE t.srno = (SELECT MAX(srno)
FROM a1
WHERE srno < a1.srno)
If you mean to say,
you want Records exist in Left table but not in right then use LEFT OUTER JOIN.

Resources