How to convert left join sql query to linq to sql - sql

I have following query in SQL. I want the same operation from linq to sql.
select count(bs.sampleId),s.sampleCode from prod.Samples s
LEFT join prod.BlockedSamples bs on bs.sampleId = s.sampleId
group by s.sampleCode
having count(bs.sampleId)>0
Relation between these two tables is 1 to many. 1 sample can have multiple entries in Blocked Sample.

What about
from s in context.Samples
join bs in context.BlockedSamples on s.sampleId
equals bs.sampleId into ps
from p in ps.DefaultIfEmpty()
group p by s.sampleCode into grouped where grouped.Count(t=>t.sampleId != null)>0
select new {key=grouped.Key,Count =
grouped.Count(t=>t.sampleId != null)}

For this and future efforts of converting SQL to LINQ you can use:
sqltolinq

Related

How to fix SQL query to Left Join a subquery with Where clause?

I'm new to SQL and I'm not certain why I am getting this error. I am trying to left join a sub-query to another query in sql developer.
This is the first query,
SELECT DISTINCT
tl.species,
ag.age
FROM
age_list ag,
tree_list tl
WHERE
ag.tree_id = tl.tree_id
And then the sub-query I would like to left join where the tree_id = tree_number is,
SELECT DISTINCT
sl.tree_spon,
sl.tree_number
FROM spon_list sl
WHERE
sl.tree_spon < 10
When trying to do this I've tried to use,
SELECT DISTINCT
tl.species,
ag.age,
q1.tree_spon
FROM
age_list ag,
tree_list tl
LEFT OUTER JOIN (SELECT DISTINCT
sl.tree_spon,
sl.tree_number
FROM spon_list sl
WHERE sl.tree_spon < 10) q1 on q1.tree_number = tree_list.tree_id
WHERE
ag.tree_id = tl.tree_id
Whatever I change in terms of the alias' for the columns and tables I always get the error, "ORA-00904: invalid identifier error", and that "tree_list.tree_id is invalid identifier", though separately the queries run fine.
Can anyone help, is it an issue with both queries joining on the tl.tree_id?
You can use the ANSI join syntax throughout (rather than mixing in legacy comma joins), joining on ag.tree_id = sl.tree_number (or tl.tree_id = sl.tree_number but they're both equal given the previous join) and putting the filter on sl.tree_spon < 10 into the ON clause as well:
SELECT DISTINCT
tl.species,
ag.age,
sl.tree_spon,
sl.tree_number
FROM age_list ag
INNER JOIN tree_list tl
ON (ag.tree_id = tl.tree_id)
LEFT OUTER JOIN spon_list sl
ON (ag.tree_id = sl.tree_number AND sl.tree_spon < 10)
Change tree_list.tree_id to tl.tree_id

Convert SQL query to Linq query with left outer join and where clause

I want to convert this SQL query to a Linq query
select
prsnRolIDTitle, prprdID
from
Tbl_RoleDetail
left outer join
Tbl_PersonRolPersonRolDetail on Tbl_RoleDetail.prsnRolDID = Tbl_PersonRolPersonRolDetail.prsnRolDID
and Tbl_PersonRolPersonRolDetail.prsnRolID = 6
Thanks for helping!
Maybe something like this:
from rd in Tbl_RoleDetail
from Tbl_PersonRolPersonRolDetail.Where(t => t.prsnRolID = 6 && t.prsnRolDID == rd.prsnRolDID).DefaultIfEmpty()
select new {rd.prsnRolIDTitle, prd.prprdID}

SQL to LINQ with outer joins and count

I am trying to write the LINQ statement for the following OUTER JOIN with COUNT but can't seem to work it out..
My LINQ skills aren't what they should be yet so any pointer would be greatly appreciated.
The SQL statement in question is:
SELECT b.Id,
b.Text,
b.Active,
COUNT(u.BusinessArea_Id)
FROM dbo.[User] AS u RIGHT OUTER JOIN dbo.BusinessArea AS b ON b.Id = u.BusinessArea_Id
GROUP BY b.Id, b.Text, Active
ORDER BY b.Id
I think you can use a linq like this:
var res = (from ba in businessAreas
let count = users.Count(u => u.BusinessArea_Id == ba.Id)
orderby ba.Id
select new {ba.Id, ba.Text, ba.Active, Count = count}
).ToList();

How to optimize Sybase Sql query?

I have one SQL query that fetches data from Sybase database. In the where clause we use text columns based on the requirement (BU IN ('CMBS','MBS') AND RU='GBR'). These clauses are killing the performance. The tables used have large number of rows.
Any suggestions to improve performance?
Below is the SQL-
SELECT [COLUMN LIST]
from dealer_Key dk,
INNER JOIN d_posting dp ON dk.deal_key_id = dp.deal_key_id,
INNER JOIN d_p_v dpv ON dp.posting_id = dpv.posting_id,
INNER JOIN snapInfo s ON dpv.snapshot_start_id = s.snapshot_id,
INNER JOIN psgl_ratemeter r ON (dp.gl_currency = r.from_currency),
INNER JOIN psgl_ratemeter_value rv (ON r.psgl_rate_id = rv.psgl_rate_id AND rv.refdate = dpv.gl_transaction_effective_date)
where
r.snapshot_end_id is null
and r.to_currency = 'AUD'
and (dp.snapshot_end_id is null or dp.snapshot_end_id > dpv.snapshot_start_id)
and dpv.gl_transaction_effective_date > '20140930'
and dpv.gl_transaction_effective_date < '20150901'
and gl_business_unit IN ('CTCMB')
and gl_currency='CAD'
and gl_counterparty='IMCLIMTR'
and gl_location='SYD'
and gl_department='LTFSY'
and gl_product='FEES'

Complex SQL Query to NHibernate DetachedCriteria or HQL

I have the following SQL Query returning the results I need:
SELECT
Person.FirstName,Person.LastName,OrganisationUnit.Name AS UnitName, RS_SkillsArea.Name AS SkillsArea, Activity.Name AS ActivityName, Activity.CLASS, Activity.StartsOn, Activity.EndsOn,
SUM(ActivityCost.CostAmount) /
NULLIF(
(
SELECT COUNT(Registration.ActivityId) FROM
Registration INNER JOIN AttemptResultsSummary ON Registration.CurrentResultId = AttemptResultsSummary.AttemptResultsSummaryId AND
Registration.RegistrationId = AttemptResultsSummary.RegistrationId
WHERE (Registration.Status = 1) AND (Registration.ActivityId = Activity.ActivityId)
AND (AttemptResultsSummary.AttendanceStatus <> 1)
)
,0)
AS IndividualCost
FROM Registration AS Registration_1 INNER JOIN
Activity ON Registration_1.ActivityId = Activity.ActivityId INNER JOIN
Person ON Registration_1.PersonId = Person.PersonId INNER JOIN
OrganisationUnit ON Person.OrganisationUnitId = OrganisationUnit.OrganisationUnitId INNER JOIN
AttemptResultsSummary ON Registration_1.CurrentResultId = AttemptResultsSummary.AttemptResultsSummaryId AND
Registration_1.RegistrationId = AttemptResultsSummary.RegistrationId AND Activity.ActivityId = AttemptResultsSummary.ActivityId AND
Person.PersonId = AttemptResultsSummary.PersonId INNER JOIN
ActivityCost ON Activity.ActivityId = ActivityCost.ActivityId LEFT OUTER JOIN
(SELECT Category.Name, Category.CategoryId
FROM Category INNER JOIN
CategoryGroup ON Category.[Group] = CategoryGroup.CategoryGroupId
WHERE (CategoryGroup.Name = N'Skills Area')) AS RS_SkillsArea INNER JOIN
ActivityInCategory ON RS_SkillsArea.CategoryId = ActivityInCategory.CategoryId ON Activity.ActivityId = ActivityInCategory.ActivityId
AND AttemptResultsSummary.AttendanceStatus <> 1
GROUP BY RS_SkillsArea.Name, Person.FirstName,Person.LastName,Activity.Name, Activity.CLASS, Activity.StartsOn, Activity.EndsOn, Activity.ActivityId, OrganisationUnit.Name,
AttemptResultsSummary.CompletionStatus, AttemptResultsSummary.AttendanceStatus
HAVING AttemptResultsSummary.AttendanceStatus <> 1
Essentially is there any way using either DetachedCriteria or HQL to do the same against the entities rather than direct SQL?
The two challenges are:
The query for cost calculation per row.
The derived table join (which needs to be an outer join as this value may not exist)
I'd appreciate any pointers. I'd rather not use SQL because of infrastructure changes and the issues with (lack of) refactoring support
Take a look at the official HQL examples # http://docs.jboss.org/hibernate/stable/core/reference/en/html/queryhql.html#queryhql-examples .
In my opinion, the 'derived joins' would be even easier to pull off using HQL.
In the case of performance, my first start would be to catch how much it costs using native SQL using your prefered profiler, and then how much it costs on NHibernate using NHProf.