How to convert this SQL into a LINQ QUERY - sql

I am having trouble turning the following sql code into LINQ. I have it mostly working but I can't figure out how to get the revision from the items table which is gotten in those subqueries. Any help would greatly be appreciated.
Here is the SQL query:
SELECT
dbo.SerialOptCon.GROUPID, TopRevsion.RevName AS NAME,
dbo.SerailOptionNo.PartNo, dbo.SerialOptCon.PRICE,
0.00 AS DISCOUNT,
dbo.GroupConfig.CURRENCY,
'OPTION' AS TYPE, dbo.SerialModelGroupOptions.MODEL,
dbo.SerialModelGroupOptions.SEQUENCE
FROM
dbo.SerialModelGroupOptions
INNER JOIN
dbo.SerialOptCon
INNER JOIN
dbo.SerailOptionNo ON dbo.SerialOptCon.OptionId = dbo.SerailOptionNo.ProductOptionId
ON dbo.SerialModelGroupOptions.OptionPartNo = dbo.SerailOptionNo.PartNo
LEFT OUTER JOIN
dbo.GroupConfig ON dbo.SerialOptCon.GROUPID = dbo.GroupConfig.ID
LEFT OUTER JOIN
(SELECT itm1.PartNo, itm1.Revision, itm1.RevName
FROM dbo.Items AS itm1
INNER JOIN
(SELECT PartNo, MAX(Revision) AS Revision
FROM dbo.Items
GROUP BY PartNo) AS itm2 ON itm1.PartNo = itm2.PartNo
AND itm1.Revision = itm2.Revision) AS TopRevsion ON dbo.SerailOptionNo.PartNo = TopRevsion.PartNo
WHERE
(dbo.SerialOptCon.GROUPID = '01d2b4d2-ad63-4eab-a83f-f31ea0f6274b')
AND (dbo.SerialModelGroupOptions.MODEL = 'abcde')
ORDER BY
SEQUENCE
Here is the LINQ query that I have currently:
foreach (var item in priceGroupDetailsViewModels)
{
(from pmo in _context.SerialModelGroupOptionss
join po in _context.SerailOptionNos on pmo.OptionPartNo equals po.PartNo
join pop in _context.dbo.SerialOptCon on po.SerailOptionNoId equals pop.SerailOptionNoId
join con in _context.GroupConfig on pop.GroupId equals con.GroupId
into p
from pmp in p.DefaultIfEmpty()
join it in _context.Items on po.PartNo equals it.PartNo
where pmp.PriceGroupId == item.PriceGroupId && pmo.Model == item.Name
select new OptionsDetails
{
GroupId = pop.GroupId,
PartNo = po.PartNo,
Currency = pmp.Currency,
Sequence = pmo.Sequence,
Description = it.Description3
});
}

Related

How to left join tables in LINQ TO SQL to get associated records

I have a linq to sql statement where I am doing join with a bunch of tables , but I need to left join a table as we are not sure if there be any associated records.
We are left joing as we are not sure if every purchase will have a file associated.
Purchase Join - Invc
Purchase Join - FileStore FileStore##Entity
select * from Purchase p
join Invc i on i.Invc_ID = p.Invc_ID
left join FileStore##Entity fe on p.Purchase_ID = fe.Entity_ID
left join FileStore fs on fs.FileStore_ID = fe.FileStore_ID
where p.Purchase_ID = 53
My current linq to sql works for the regular join , how can I left join the file store and store entity table
PurchaseEntity purchase = (from p in TransactionalDbContext.Purchase
join i in TransactionalDbContext.Invc
on p.InvcId equals i.InvcId
where d.Purchase_Id == id
select new DisputeEntity
{
Purchase_Id = p.Purchase_Id,
InvcId = i.InvcId,
SubmittedDate = d.SubmitDt,
InvcNum = i.InvcNum
// get the file elements by left join file
}).FirstOrDefault();
You can easily perform left or right joins by playing with the DefaultIfEmpy method.
Following your example:
from p in dbContext.Purchases
join i in dbContext.Invc on p.InvcId equals i.InvcId
join fe in dbContext.FileStoreEntities.DefaultIfEmpty() on p.Purchase_ID equals fe.Entity_ID
join fs in dbContext.FileStores.DefaultIfEmpty() on fe.FileStore_ID equals fs.FileStore_ID

Access Query - Group by and Max

I have been working on this for a few hours now and just can not figure it out.
How would I go about sorting this query by enco_id and only having the max of each clpr_id show up. for example:
Here is my MSAccess Sql Code
SELECT dbo_Client.med_rec_no, dbo_Encounter.episode_number, dbo_client_program.enco_id, dbo_client_program.clpr_id, dbo_client_program.prle_id, dbo_PROGRAM_LEVEL.prle_name, dbo_Client.fname, dbo_Client.lname, dbo_DISCHARGE_STATUS.dist_name, DS2.dist_name
FROM (((((dbo_Client INNER JOIN dbo_Encounter ON dbo_Client.client_id = dbo_Encounter.client_id) INNER JOIN dbo_Episode_info ON dbo_Encounter.enco_id = dbo_Episode_info.enco_id) INNER JOIN dbo_DISCHARGE_STATUS ON dbo_Episode_info.dist_id = dbo_DISCHARGE_STATUS.dist_id) INNER JOIN dbo_client_program ON dbo_Encounter.enco_id = dbo_client_program.enco_id) INNER JOIN dbo_DISCHARGE_STATUS AS DS2 ON dbo_client_program.dist_id = DS2.dist_id) INNER JOIN dbo_PROGRAM_LEVEL ON dbo_client_program.prle_id = dbo_PROGRAM_LEVEL.prle_id;
Also here is what my query looks like
EDIT:
This is the code I am trying to use now and it still is not working
SELECT dbo_Client.client_id, dbo_Client.med_rec_no, dbo_Encounter.episode_number, dbo_Encounter.start_date, dbo_Encounter.end_date, dbo_client_program.clpr_id, dbo_client_program.enco_id, dbo_PROGRAM_LEVEL.prle_name, dbo_Client.fname, dbo_Client.lname, dbo_DISCHARGE_STATUS.dist_name, DS2.dist_name
FROM (((((dbo_Client INNER JOIN dbo_Encounter ON dbo_Client.client_id = dbo_Encounter.client_id) INNER JOIN dbo_Episode_info ON dbo_Encounter.enco_id = dbo_Episode_info.enco_id) INNER JOIN dbo_DISCHARGE_STATUS ON dbo_Episode_info.dist_id = dbo_DISCHARGE_STATUS.dist_id) INNER JOIN dbo_client_program ON dbo_Encounter.enco_id = dbo_client_program.enco_id) INNER JOIN dbo_DISCHARGE_STATUS AS DS2 ON dbo_client_program.dist_id = DS2.dist_id) INNER JOIN dbo_PROGRAM_LEVEL ON dbo_client_program.prle_id = dbo_PROGRAM_LEVEL.prle_id
WHERE dbo_client_program.clpr_id IN
(SELECT TOP 1 clpr_id FROM dbo_client_program as New
WHERE New.clpr_id = dbo_client_program.clpr_id
ORDER by dbo_client_program.clpr_id DESC) AND (dbo_DISCHARGE_STATUS.dist_name <> DS2.dist_name) AND dbo_Encounter.start_date > #1/1/2020# AND dbo_Encounter.end_date > #1/1/2020#
ORDER BY dbo_Encounter.episode_number;
As you are still understanding the aggregate queries my suggestion is:
1-Create a query where you group by all fields and max(clpr_id). Save this as "Query1"
2-Create another query based on "Query1" and sort by "enco_id "

Passing different column values to where clause

SELECT pims.icicimedicalexaminerreport.id,
pims.icicimerfemaleapplicant.adversemenstrualid,
pims.icicimerfemaleapplicant.pregnantid,
pims.icicimerfemaleapplicant.miscarriageabortionid,
pims.icicimerfemaleapplicant.breastdiseaseid,
pims.pimscase.tiannumber
FROM pims.pimscase
INNER JOIN pims.digitization
ON pims.pimscase.digitizationid = pims.digitization.id
INNER JOIN pims.medicalexaminerreport
ON pims.digitization.medicalexaminerreportid =
pims.medicalexaminerreport.id
INNER JOIN pims.icicimedicalexaminerreport
ON pims.medicalexaminerreport.id =
pims.icicimedicalexaminerreport.id
INNER JOIN pims.icicimerfemaleapplicant
ON pims.icicimedicalexaminerreport.id =
pims.icicimerfemaleapplicant.id
WHERE pims.pimscase.tiannumber = 'ICICI1234567890'
which gives me the following output
Now I want to use the above output values to select the rows from the table "YesNoAnswerWithObservation"
I imagine it should look something like this Select * from YesNoAnswerWithObservation Where Id in (22,27,26,...23)
Only instead of typing the values inside IN clause I want to use the values in each column resulting from above-mentioned query.
I tried the below code but it returns all the rows in the table rather than rows mentioned inside the In
SELECT pims.yesnoanswerwithobservation.observation,
graphitegtccore.yesnoquestion.description,
pims.yesnoanswerwithobservation.id ObservationId
FROM pims.yesnoanswerwithobservation
INNER JOIN graphitegtccore.yesnoquestion
ON pims.yesnoanswerwithobservation.yesnoanswerid =
graphitegtccore.yesnoquestion.id
WHERE EXISTS (SELECT pims.icicimedicalexaminerreport.id,
pims.icicimerfemaleapplicant.adversemenstrualid,
pims.icicimerfemaleapplicant.pregnantid,
pims.icicimerfemaleapplicant.pelvicorgandiseaseid,
pims.icicimerfemaleapplicant.miscarriageabortionid,
pims.icicimerfemaleapplicant.gynocologicalscanid,
pims.icicimerfemaleapplicant.breastdiseaseid,
pims.pimscase.tiannumber
FROM pims.pimscase
INNER JOIN pims.digitization
ON pims.pimscase.digitizationid =
pims.digitization.id
INNER JOIN pims.medicalexaminerreport
ON pims.digitization.medicalexaminerreportid =
pims.medicalexaminerreport.id
INNER JOIN pims.icicimedicalexaminerreport
ON pims.medicalexaminerreport.id =
pims.icicimedicalexaminerreport.id
INNER JOIN pims.icicimerfemaleapplicant
ON pims.icicimedicalexaminerreport.id =
pims.icicimerfemaleapplicant.id
WHERE pims.pimscase.tiannumber = 'ICICI1234567890')
Any help or a nudge in the right direction would be greatly appreciated
Presumably you want the ids from the first query:
SELECT awo.observation, ynq.description, ynq.id as ObservationId
FROM pims.yesnoanswerwithobservation awo JOIN
graphitegtccore.yesnoquestion ynq
ON awo.yesnoanswerid = ynq.id
WHERE ynq.id = (SELECT mer.id
FROM pims.pimscase c JOIN
pims.digitization d
ON c.digitizationid = d.id JOIN
pims.medicalexaminerreport mer
ON d.medicalexaminerreportid = mer.id JOIN
pims.icicimedicalexaminerreport imer
ON mer.id = imer.id JOIN
pims.icicimerfemaleapplicant ifa
ON imer.id = ifa.id
WHERE c.tiannumber = 'ICICI1234567890'
) ;
Notice that table aliases make the query much easier to write and to read.

Converting Inner Join Grouping SQL into Linq

I have the following SQL statement:
SELECT b.Brand_key, b.BrandName, Sum(po.Quantity) AS Quantity
FROM Brands b
INNER JOIN Products p ON b.Brand_key = p.Brand_fkey
INNER JOIN ProductOrders po ON p.Product_key = po.Product_fkey
GROUP BY b.Brand_key
ORDER BY Quantity DESC, b.BrandName ASC
which works perfectly. Distinct values are returned as expected. I've attempted to turn it into Linq, but I feel like I'm going down a rabbit hole that never ends.
var testModelTwo =
(from b in db.Brands
join p in db.Products on b.brandKey equals p.brandKey
select new { brandKey = b.brandKey, BrandName = b.BrandName, ProductKey = p.productKey }
into groupResultBP
join po in pom on groupResultBP.ProductKey equals po.Product_fkey
select new
{
brandKey = groupResultBP.brandKey,
BrandName = groupResultBP.BrandName,
Quantity = po.Quantity
} into gr
group gr by gr.brandKey into gd
select new { Brand = gd.Key, BrandCounter = gd.Sum(c => c.Quantity) } into sumGroup
select sumGroup).ToList();
This seems to get to the point where I have a key and the sum, but need to do another join to get back the brand item information with sumGroup.
I feel like I've gone round the houses about 100 times and this is much easier than I'm making it! Is what I've done so far correct?

SQL Server update with joins

I am trying to update a date in a table, based off of a MAX(date) in another table. To get the correct data to link up, I have to do 2 inner joins and 2 left outer joins.
I can select the correct data, it returns a Guid (PersonId) and the Date.
I have to use this information to update my original table. I am having trouble getting this to work, I still getting syntax errors.
update tblqualityassignments as assign
inner join tblrequirementteams as team on assign.guidmemberid = team.guidmemberid
set assign.dtmQAPCLed = dtmTaken
from
(
select reg.guidpersonid, max(certs.dtmTaken) as dtmTaken from tblqualityassignments as assign
inner join tblrequirementteams as team on assign.guidmemberid = team.guidmemberid
inner join tblregisteredusercerts as reg on team.guidpersonid = reg.guidpersonid
left outer join tblcerttaken as certs on certs.guidcertid = reg.guidcertid
left outer join tblCodesCertType as types on types.intcerttypeid = certs.intcerttypeid
where types.intcerttypeid = 1
and assign.guidmemberid = team.guidmemberid
group by reg.guidpersonid as data
)
where data.guidpersonid = team.guidpersonid
Assuming you are using SQL Server for this, then this should work:
UPDATE A
SET A.dtmQAPCLed = dtmTaken
FROM tblqualityassignments AS A
INNER JOIN tblrequirementteams as T
ON A.guidmemberid = T.guidmemberid
INNER JOIN (select reg.guidpersonid, max(certs.dtmTaken) as dtmTaken
from tblqualityassignments as assign
inner join tblrequirementteams as team
on assign.guidmemberid = team.guidmemberid
inner join tblregisteredusercerts as reg
on team.guidpersonid = reg.guidpersonid
left outer join tblcerttaken as certs
on certs.guidcertid = reg.guidcertid
left outer join tblCodesCertType as [types]
on [types].intcerttypeid = certs.intcerttypeid
where [types].intcerttypeid = 1
and assign.guidmemberid = team.guidmemberid
group by reg.guidpersonid) data
ON T.guidpersonid = data.guidpersonid