SQL to LINQ - AND Statement in Left Join - sql

I have this SQL query to get all police name that didn't assigned to specified police car.
SELECT policename
FROM police
LEFT OUTER JOIN policecar
ON police.policeid = policecar.policeid
AND carid = 1
WHERE policecar.policeid IS NULL
I want to convert that query to LINQ but I have difficulty to convert AND and WHERE statement. Please give me any direction on this, thanks.

Try this:
var result =
from police in polices
join policecar in policecars.Where(x => x.carid == 1)
on police.policeId equals policecar.policeId into res
where !res.Any()
select police.policeName;

Related

How to select all rows that are related to satisfied condition in ms ACCESS

I have the following data in table VehiclesAccSummary:
I am not sure how to do this but what I want is a query that would return all rows where there where only two car in the accident and it was a head on crash so in both cars PointOfImpact was 'Front' i know in need to do some inner join on the same table but i don' want to join same car with it self. Any idea ?
The end result should be something like this
You can use a subquery to count the number of "Front' records for each AccRef.
SELECT *
FROM VehiclesAccSummary INNER JOIN
(SELECT VehiclesAccSummary.AccRef, Count(VehiclesAccSummary.PointOfImpact) AS CountOfPointOfImpact FROM VehiclesAccSummary GROUP BY VehiclesAccSummary.AccRef, VehiclesAccSummary.PointOfImpact HAVING VehiclesAccSummary.PointOfImpact="Front") AS FrontCount
ON VehiclesAccSummary.AccRef = FrontCount.AccRef
WHERE VehiclesAccSummary.NumCars = 2 AND CountOfPointOfImpact = 2;
This will limit the records to AccRefs with NumCar = 2 and the count of Front records = 2.
Edit: Since the same car can be listed in multiple records, we need a new approach. Try this:
SELECT VehiclesAccSummary.*, Subquery.CountOfPointOfImpact
FROM VehiclesAccSummary LEFT JOIN (SELECT VehiclesAccSummary.AccRef, Count(VehiclesAccSummary.PointOfImpact) AS CountOfPointOfImpact
FROM VehiclesAccSummary
WHERE (((VehiclesAccSummary.PointOfImpact)<>"Front"))
GROUP BY VehiclesAccSummary.AccRef) AS Subquery ON VehiclesAccSummary.AccRef = Subquery.AccRef
WHERE (((Subquery.CountOfPointOfImpact) Is Null));
Instead of confirming that the count of front accidents is 2, this confirms that the count of non-front accidents is 0.

MS Access Subquery

The sql queries below need to be combined so that it further reduces the results. One of these will need to be a subquery. I am newbie with Access and am only getting errors. The end result should further filter the results to only show the encounters meeting all criteria in both of the querys. Both of these result in the correct result individually...any help you could provide would be greatly appreciated.
SELECT encounters.encounter_id, medications.encounter_id,
medications.medication_id, medication_types.medication_id,
medication_types.name, medication_types.class
FROM medication_types
INNER JOIN (encounters
INNER JOIN medications ON encounters.encounter_id = medications.encounter_id)
ON medication_types.medication_id = medications.medication_id
WHERE medication_types.class LIKE '*Antibiotic*';
SELECT encounters.encounter_id, encounters.admit_year,
diseases.encounter_id, diseases.disease_id,
disease_types.disease_id, disease_types.icd9cm
FROM encounters
INNER JOIN (disease_types
INNER JOIN diseases ON disease_types.disease_id = diseases.disease_id)
ON encounters.encounter_iD = diseases.encounter_id
WHERE disease_types.icd9cm IN ('041.3','480.0','480.1','480.2','480.3','480.8','480.9','481','482.1','482.2','482.9','486','V03.82','V12.61')
AND admit_week BETWEEN 5 and 9
AND encounters.admit_year = 2014
ORDER BY encounters.admit_week;
If you don't need to display the medications and diseases, just return the encounter info, consider:
SELECT DISTINCT encounters.encounter_id, admit_year FROM Query2 WHERE encounters.encounter_id IN (SELECT encounters.encounter_id FROM Query1);

How can I do a SQL join to get a value 4 tables farther from the value provided?

My title is probably not very clear, so I made a little schema to explain what I'm trying to achieve. The xxxx_uid labels are foreign keys linking two tables.
Goal: Retrieve a column from the grids table by giving a proj_uid value.
I'm not very good with SQL joins and I don't know how to build a single query that will achieve that.
Actually, I'm doing 3 queries to perform the operation:
1) This gives me a res_uid to work with:
select res_uid from results where results.proj_uid = VALUE order by res_uid asc limit 1"
2) This gives me a rec_uid to work with:
select rec_uid from receptor_results
inner join results on results.res_uid = receptor_results.res_uid
where receptor_results.res_uid = res_uid_VALUE order by rec_uid asc limit 1
3) Get the grid column I want from the grids table:
select grid_name from grids
inner join receptors on receptors.grid_uid = grids.grid_uid
where receptors.rec_uid = rec_uid_VALUE;
Is it possible to perform a single SQL that will give me the same results the 3 I'm actually doing ?
You're not limited to one JOIN in a query:
select grids.grid_name
from grids
inner join receptors
on receptors.grid_uid = grids.grid_uid
inner join receptor_results
on receptor_results.rec_uid = receptors.rec_uid
inner join results
on results.res_uid = receptor_results.res_uid
where results.proj_uid = VALUE;
select g.grid_name
from results r
join resceptor_results rr on r.res_uid = rr.res_uid
join receptors rec on rec.rec_uid = rr.rec_uid
join grids g on g.grid_uid = rec.grid_uid
where r.proj_uid = VALUE
a small note about names, typically in sql the table is named for a single item not the group. thus "result" not "results" and "receptor" not "receptors" etc. As you work with sql this will make sense and names like you have will seem strange. Also, one less character to type!

Convert a SQL query to LINQ query

I have the following SQL query
SELECT *
FROM LOC l
JOIN CLA c ON l.IdLoc = c.IdLoc
JOIN FA f on c.IdCla = f.IdCla
LEFT JOIN CON co ON f.IdCla = co.IdCla
AND co.DeletedDate IS NULL
AND co.IdUser = f.IdUser
WHERE f.IdUser = 7
AND f.DeletedDate IS NULL
I would like to convert it to LINQ but I'm absolutely not at ease with LEFT JOIN and "temp table" with LINQ.
Moreover, I tried to convert it but it seems it is impossible to create a join clause with a WHERE inside in LINQ (Linqer told me that and Linqpad doesn't seem able to convert from SQL to LINQ in free version)
Could you give me clue ?
Thanks a lot
I think you are looking for something like this. I left out the select clause so that you can pull out what you need. Things to note:
To join multiple columns, create anonymous types. The field names in the anonymous types must match.
To create a =NULL condition, create a variable name that matches the field name in the other entity. Set it =null but coerce it to the nullable data type of the field you are setting it equal to.
Edit: Updated query to move where clause to joins
from l in LOC
join c in CLA
on l.IdLoc equals c.IdLoc
join f in FA
on new { c.IdCla, IdUser = 7, DeletedDate = (DateTime?)null }
equals new { f.IdCla, f.IdUser, f.DeletedDate }
join co in CON
on new { f.IdCla, DeletedDate = (DateTime?)null, f.IdUser }
equals new { co.IdCla, co.DeletedDate, co.IdUser } into lj
from l in lj.DefaultIfEmpty()

LINQ to SQL: Left join a table with itself and compute an average

I'm trying to write the following query in LINQ to SQL. The table contains a list of sessions arranged by users, and the query computes the average amount of time between consecutive sessions for each user. It uses a left join, so that users who have only one session have a NULL value.
SELECT t1.workerId, AVG(DATEDIFF(s, t1.endTime, t2.startTime))
FROM e_userLongSessions t1
LEFT JOIN e_userLongSessions t2
ON t1.workerId = t2.workerId AND t1.sessionNum = t2.sessionNum - 1
GROUP BY t1.workerId
ORDER BY t1.workerId
Based on the questions LINQ to SQL Left Outer Join and How to do joins in LINQ on multiple fields in single join, I've gotten to the following query:
from s1 in gzClasses.e_userLongSessions
join s2 in gzClasses.e_userLongSessions
on new {w = s1.workerId, n = s1.sessionNum} equals new {w = s2.workerId, n = s2.sessionNum - 1}
into joined
from s2 in joined.DefaultIfEmpty(null)
group new {s1, s2} by s1.workerId into g
select g.Average(e => e.s2 == null ? (double?) null : (e.s2.startTime - e.s1.endTime).TotalSeconds);
I'm getting a Unsupported overload used for query operator 'DefaultIfEmpty' message. Any suggestions?
Your LINQ query is not structured the same way the T-SQL query is. Specifically, you are only including s in the grouping. In fact, s is named in a misleading way. It should be s2. Include both:
from s1 in gzClasses.e_userLongSessions
join s2 in gzClasses.e_userLongSessions
on new {w = s1.workerId, n = s1.sessionNum}
equals new {w = s2.workerId, n = s2.sessionNum - 1}
into joined
from s2Null in joined.DefaultIfEmpty()
group new {s1, s2Null} by s1.workerId into g
orderby g.Key // workerId
select g.Average(e => (e.s2Null.startTime - e.s1.endTime).TotalSeconds);
Now, you have data from both tables available in the aggregate. I don't think both of your queries are taking into account that s2.startTime can be null. But that is a bug that is not the point of the question.