SQL statement and LINQ returning different amount of data - sql

I'm trying to convert a SQL statement to LINQ and for some reason the result sets I'm getting are different. The SQL is returning more data than the LINQ.
This is the SQL Query:
SELECT DISTINCT ssLookup.StopID,
dc.CityName,
dc.StateAbbrev,
sc.CarrierID,
sc.CarrierCode,
sc.CarrierName
FROM ScheduleDestinationCache dc
INNER JOIN ScheduleStops ssFilter ON ssFilter.CarrierID = dc.CarrierID
INNER JOIN ScheduleStops ssLookup ON dc.CityID = ssLookup.StopID
INNER JOIN ScheduleCarriers sc ON ssLookup.CarrierID = sc.CarrierID
WHERE (ssFilter.StopID = 582 OR ssFilter.StopID IN
(SELECT * FROM dbo.GetTwins(582)))
ORDER BY dc.CityName, dc.StateAbbrev
This is the LINQ statement:
(from sdc in ScheduleDestinationCaches
let twins = GetTwins(582).Select(gt => gt.StopIDs)
join ssFilter in ScheduleStops on sdc.CarrierID equals ssFilter.CarrierID
join ssLookup in ScheduleStops on sdc.CityID equals ssLookup.CityID
join sc in ScheduleCarriers on ssLookup.CarrierID equals sc.CarrierID
where ssFilter.StopID == 582 || twins.Contains(ssFilter.StopID)
orderby sdc.CityName, sdc.StateAbbrev
select new {
ssLookup.StopID,
sdc.CityName,
sdc.StateAbbrev,
sc.CarrierID,
sc.CarrierCode,
sc.CarrierName
}).GroupBy(g => new
{
g.StopID,
g.CityName,
g.StateAbbrev,
g.CarrierID,
g.CarrierCode,
g.CarrierName
})
What am I doing wrong?
Thank you in advance.

Related

How to convert this SQL into a LINQ QUERY

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
});
}

Laravel query builder join using either one of two conditions

I have a complex query that I want to use either Query Builder or Eloquent (preferred) but I'm struggling with an inner join.
The inner join needs to be one of either of 2 conditions so if one fails, the other is used.
This is my original query
SELECT DISTINCT tableA.crmid, tableB.*
FROM tableB
INNER JOIN tableA ON tableA.crmid = tableB.customaccountsid
INNER JOIN tableC ON (tableC.relcrmid = tableA.crmid OR tableC.crmid = tableA.crmid)
WHERE tableA.deleted = 0 AND tableC.relcrmid = 123 AND tableC.relation_id = 186
This is my attempt at using Query Builder and I know where the problem lies. It's where I join tableC. I don't know how to use my condition there
DB::table('tableB')
->join('tableA', 'tableA.crmid', '=', 'tableB.customaccountsid')
->join('tableC', function($join) {
$join->on(DB::raw('(tableC.relcrmid = tableA.crmid OR tableC.crmid = tableA.crmid)'));
})
->where('tableA.deleted', 0)
->where('tableC.relcrmid', 3727)
->where('tableC.relation_id', 186)
->select('tableA.crmid', 'tableB.*')
Ant this is the output of the query when i output as SQL
SELECT `tableA`.`crmid`, `tableB`.*
FROM `tableB`
INNER JOIN `tableA` ON `tableA`.`crmid` = `tableB`.`customaccountsid`
INNER JOIN `tableC` ON `tableC`.`relcrmid` = (tableC.relcrmid = tableA.crmid OR tableC.crmid = tableA.crmid)
WHERE `tableA`.`deleted` = ? AND `tableC`.`relcrmid` = ? AND `tableC`.`relation_id` = ?
Just try this:
->join('tableC', function ($join){
$join->on(function($query){
$query->on('tableC.relcrmid', '=', 'tableA.crmid')
->orOn('tableC.crmid', '=', 'tableA.crmid');
});
})
It returns as in your original query:
INNER JOIN tableC ON (tableC.relcrmid = tableA.crmid OR tableC.crmid = tableA.crmid)

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();

Hibernate hql query

How can i express this SQL query in HQL if we say i have the correct mappings, dtos(pojo) and configurations files...
select * from sig_tc_contraloria_objetivos o
inner join sig_tc_contraloria_iniciativas i on o.id_objetivo = i.id_objetivo
inner join sig_tc_contraloria_acciones a on i.id_iniciativa = a.id_iniciativa
where a.id_organizacion = 8;
I expect as a result a List of objetivos(Parent) -> Iniciativas(Child) -> Acciones(Child)
I was trying in this way:
String sql = "select distinct p from SigTcContraloriaObjetivos p join p.children c join c.children b where b.idOrganizacion = 8";
assuming correct mapping and configuration the following should work
String sql = "select distinct p from SigTcContraloriaObjetivos p join p.children c join c.children b where b.idOrganizacion = 8";
the difference is in the where clause. You had an and right after where and that's illegal syntax.

Convert advanced SQL query with nested joins to Linq-to-sql

I have ran into a snag with my Linq-to-Sql.
I have a sql query that runs the way I want and usually I use Linqer to convert to Linq to see the general idea. But this time my SQL query seems to advanced for Linqer. :/
I think the problem is the INNER JOINS that are nested in the LEFT OUTER JOIN. Unfortunately I have never ran into this before and don't know how to solve it using Linq.
My SQL query looks like this:
SELECT c.[Company], c.[Name_First], c.[Name_Last], ort.[IDOriginatorRoleType],
ort.[RoleType] AS [OriginatorRoleType], o.[IDOriginator], o.[IDWork],
o.[IDContact], m.[IDMedia], m.[IDWork], m.[FileName], m.[FileNameOnDisk],
m.[DateAdded], w.[IDWork] AS [IDWork2], w.[ArticleNumber], w.[Title],
w.[FrontPageLow], w.[FrontPageLowOnDisk], w.[FrontPageHigh],
w.[FrontPageHighOnDisk]
FROM [dbo].[tblSubscriptionsWorks] AS sw
INNER JOIN [dbo].[tblWorks] AS w ON sw.[IDWork] = w.[IDWork]
LEFT OUTER JOIN [dbo].[tblMedias] AS m ON m.[IDWork] = w.[IDWork]
LEFT OUTER JOIN ([dbo].[tblOriginators] AS o
INNER JOIN [dbo].[tblOriginatorRoles] AS ors ON
o.[IDOriginatorRole] = ors.[IDOriginatorRole]
INNER JOIN [dbo].[tblOriginatorRoleTypes] AS ort ON
ors.[IDOriginatorRoleType] = ort.[IDOriginatorRoleType]
INNER JOIN [dbo].[tblContacts] AS c ON
o.[IDContact] = c.[IDContact]) ON
(o.[IDWork] = w.[IDWork]) AND (ort.[IDOriginatorRoleType] = 1)
WHERE sw.[IDWork_Subscription] = 9942
The left outer join is not a problem what I can see. You just have to divide the statement
LEFT OUTER JOIN ([dbo].[tblOriginators] AS o
INNER JOIN [dbo].[tblOriginatorRoles] AS ors ON
o.[IDOriginatorRole] = ors.[IDOriginatorRole]
INNER JOIN [dbo].[tblOriginatorRoleTypes] AS ort ON
ors.[IDOriginatorRoleType] = ort.[IDOriginatorRoleType]
INNER JOIN [dbo].[tblContacts] AS c ON
o.[IDContact] = c.[IDContact]) ON
(o.[IDWork] = w.[IDWork]) AND (ort.[IDOriginatorRoleType] = 1)
into another IQueryable list. In the example the variable db is the datacontext. Here is a suggestion to a solution:
//selects all the columns that is just in the select from the left join
var leftJoin=
(
from o in db.tblOriginators
join ors in db.tblOriginatorRoles
on o.IDOriginatorRole equals ors.IDOriginatorRole
join ort in db.tblOriginatorRoleTypes
on ors.IDOriginatorRoleType equals ort.IDOriginatorRoleType
join c in db.tblContacts
on o.IDContact equals c.IDContact
where ort.IDOriginatorRoleType==1
select new
{
o.IDWork,
c.Company,
c.Name_First,
c.Name_Last,
ort.IDOriginatorRoleType,
ort.RoleType,
o.IDOriginator,
o.IDContact
}
);
var output=(
from sw in db.tblSubscriptionsWorks
join w in db.tblWorks
on sw.IDWork equals w.IDWork
from m in db.tblMedias
.Where(x=>x.IDWork==w.IDWork).DefaultIfEmpty()
//Left join with the IQueryable list
from org in leftJoin
.Where(x =>x.IDWork==w.IDWork).DefaultIfEmpty()
where
sw.IDWork_Subscription == 9942
select new
{
org.Company,
org.Name_First,
org.Name_Last,
org.IDOriginatorRoleType,
OriginatorRoleType=org.RoleType,
org.IDOriginator,
org.IDWork,
m.IDMedia,
m.IDWork,
m.FileName,
m.FileNameOnDisk,
w.FrontPageLow,
w.FrontPageLowOnDisk,
w.FrontPageHigh,
w.FrontPageHighOnDisk
}
);