How do I write the following sql join in linq?
select Campaign.CampaignName, COUNT(*) as total
from Campaign join CampaignAsset
on CampaignAsset.CampaignId=Campaign.CampaignId
where Campaign.UserProfileId=65
Group By Campaign.CampaignName
Try This :
YourDatabaseName dataContext = new YourDatabaseName();
var result = from c in dataContext.Campaign
join ca in dataContext.CampaignAsset on c.CampaignId equals ca.CampaignId into j1
from j2 in j1.DefaultIfEmpty()
where c.UserProfileId = 65
group j2 by c.CampaignName into grouped
select new { CampaignName = grouped.Key, Count = grouped.Count() };
Related
I have a SQL Statement like this:
select
b.ActivityRecordId, b.ActivityName, b.ActivityDetail,
b.CustomerId, e.CustomerName,
b.JobStatusId, c.JobStatusName, b.EstimateStartDate,
b.EstimateFinishDate, b.StartedDateTime, b.FinishedDateTime,
a.ActivityRecordProgressId, a.CustomerContactId,
Concat(d.FirstName, ' ', d.MiddleName, ' ', d.LastName) as fullName,
a.Started, a.Finished, a.ActivityDescription,
g.ActivityTypeId, g.ActivityTypeName, a.ActivitySubTypeId, f.ActivitySubTypeName
from
ActivityRecordProgress a
right join
ActivityRecord b on a.ActivityRecordId = b.ActivityRecordId
left join
ActivitySubType f on a.ActivitySubTypeId = f.ActivitySubTypeId
left join
ActivityType g on f.ActivityTypeId = g.ActivityTypeId
left join
CustomerContact d on a.CustomerContactId = d.CustomerContactId
inner join
JobStatus c on b.JobStatusId = c.JobStatusId
inner join
Customer e on b.CustomerId = e.CustomerId
Then I tried to convert it to Linq:
var obj = (from a in _db.ActivityRecords
join b in _db.ActivityRecordProgresses on a.ActivityRecordId equals b.ActivityRecordId into ab
from p in ab.DefaultIfEmpty()
join c in _db.Customers on a.CustomerId equals c.CustomerId
join e in _db.CustomerContacts on c.CustomerId equals e.CustomerId
join d in _db.JobStatuses on a.JobStatusId equals d.JobStatusId
join f in _db.ActivitySubTypes on p.ActivitySubTypeId equals f.ActivitySubTypeId
join g in _db.ActivityTypes on f.ActivitySubTypeId equals g.ActivityTypeId
select new OutstandingActivityViewModel {
ActivityRecordId = p.ActivityRecordId,
ActivityName = a.ActivityName,
ActivityDetail = a.ActivityDetail,
CustomerId = a.CustomerId,
CustomerName = c.CustomerName,
JobStatusId = a.JobStatusId,
JobStatusName = d.JobStatusName,
EstimateStartDate = a.EstimateStartDate,
StartedDateTime = a.StartedDateTime,
EstimateFinishDateTime = a.EstimateFinishDate,
FinishedDateTime = a.FinishedDateTime,
FirstName = e.FirstName, MiddleName = e.MiddleName, LastName = e.LastName,
Started = p.Started, Finished = p.Finished,
ActivityTypeName = g.ActivityTypeName, ActivitySubTypeName = f.ActivitySubTypeName,
ActivityDescription = p.ActivityDescription
}).ToListAsync();
But the result is not the same. The SQL result is the right one. It only 4 records. But in Linq, it appears 6 records. I'm sure I did something wrong with the linq syntax.
Can anyone show me where the mistake in my syntax is?
Really appreciated - thank you.
Thanks for commenting my question. It was very useful.
Finally I found the answer after trial and error using SQL generated. Below is the answer for the Linq syntax:
var obj = (from a in _db.ActivityRecords
join b in _db.ActivityRecordProgresses on a.ActivityRecordId equals b.ActivityRecordId into leftsatu
from leftkesatu in leftsatu.DefaultIfEmpty()
join c in _db.ActivitySubTypes on leftkesatu.ActivitySubTypeId equals c.ActivitySubTypeId into leftdua
from leftkedua in leftdua.DefaultIfEmpty()
join d in _db.ActivityTypes on leftkedua.ActivitySubTypeId equals d.ActivityTypeId into lefttiga
from leftketiga in lefttiga.DefaultIfEmpty()
join e in _db.CustomerContacts on leftkesatu.CustomerContactId equals e.CustomerContactId into leftempat
from leftkeempat in leftempat.DefaultIfEmpty()
join f in _db.JobStatuses on a.JobStatusId equals f.JobStatusId
join g in _db.Customers on a.CustomerId equals g.CustomerId
select new OutstandingActivityViewModel
{
ActivityRecordId = a.ActivityRecordId,
ActivityName = a.ActivityName,
ActivityDetail = a.ActivityDetail,
CustomerId = a.CustomerId,
CustomerName = g.CustomerName,
JobStatusId = a.JobStatusId,
JobStatusName = f.JobStatusName,
EstimateStartDate = a.EstimateStartDate,
StartedDateTime = a.StartedDateTime,
EstimateFinishDateTime = a.EstimateFinishDate,
FinishedDateTime = a.FinishedDateTime,
FirstName = leftkeempat.FirstName,
MiddleName = leftkeempat.MiddleName,
LastName = leftkeempat.LastName,
Started = leftkesatu.Started,
Finished = leftkesatu.Finished,
ActivityTypeName = leftketiga.ActivityTypeName,
ActivitySubTypeName = leftkedua.ActivitySubTypeName,
ActivityDescription = leftkesatu.ActivityDescription
}
);
It will generate SQL like:
SELECT [a].[ActivityRecordId], [a].[ActivityName], [a].[ActivityDetail], [a].[CustomerId], [c0].[CustomerName], [a].[JobStatusId], [j].[JobStatusName],
[a].[EstimateStartDate], [a].[StartedDateTime], [a].[EstimateFinishDate] AS [EstimateFinishDateTime], [a].[FinishedDateTime],
[c].[FirstName], [c].[MiddleName], [c].[LastName],
[a0].[Started], [a0].[Finished], [a2].[ActivityTypeName], [a1].[ActivitySubTypeName], [a0].[ActivityDescription]
FROM [ActivityRecord] AS [a]
LEFT JOIN [ActivityRecordProgress] AS [a0] ON [a].[ActivityRecordId] = [a0].[ActivityRecordId]
LEFT JOIN [ActivitySubType] AS [a1] ON [a0].[ActivitySubTypeId] = [a1].[ActivitySubTypeId]
LEFT JOIN [ActivityType] AS [a2] ON [a1].[ActivitySubTypeId] = [a2].[ActivityTypeId]
LEFT JOIN [CustomerContact] AS [c] ON [a0].[CustomerContactId] = [c].[CustomerContactId]
INNER JOIN [JobStatus] AS [j] ON [a].[JobStatusId] = [j].[JobStatusId]
INNER JOIN [Customer] AS [c0] ON [a].[CustomerId] = [c0].[CustomerId]
I'm struggling with this SQL consult, the error message is:
1055 - Expression #10 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'ctrl2019.s.cgsc_cuenta' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by.
And here is the code:
SELECT c.cgcu_cuenta AS id,
g.ger_cuenta, g.ger_nombre,
p.cgp_cuenta, p.cgp_nombre,
r.rub_cuenta, r.rub_nombre,
c.cgcu_cuenta, c.cgcu_nombre,
s.cgsc_cuenta, s.cgsc_nombre,
SUM(IFNULL(a.debe, 0)) - SUM(IFNULL(a.haber, 0)) AS debe, 0 AS haber,
'D' AS nat_id,
c.cgcu_cuenta AS cuenta, c.cgcu_nombre AS nombre
FROM ctrl2019.cat_Genero g
INNER JOIN ctrl2019.cat_CgGrupo p USING(ger_id)
INNER JOIN ctrl2019.cat_Rubro r USING(ger_id, cgp_id)
INNER JOIN ctrl2019.cat_CgCuenta c USING(ger_id, cgp_id, rub_id)
INNER JOIN ctrl2019.cat_CgSubcuenta s USING(ger_id, cgp_id, rub_id, cgcu_id)
LEFT JOIN (
SELECT a.ger_id, a.grp_id, a.rub_id, a.cta_id, a.sct_id,
SUM(IFNULL(a.msl_debe, 0)) AS debe, SUM(IFNULL(a.msl_haber, 0)) AS haber
FROM ldf.vin_EntePublicoLDF e
INNER JOIN ldf.blz_Mensual_2019 a USING(gpo_id, ur_id)
WHERE e.ejr_id = 2019
AND a.ger_id = 1
AND e.ent_id = 12
AND a.msc_id IN (0, 1, 2, 3)
GROUP BY a.ger_id, a.grp_id, a.rub_id, a.cta_id, a.sct_id
)a ON s.ger_id = a.ger_id AND s.cgp_id = a.grp_id AND s.rub_id = a.rub_id AND s.cgcu_id = a.cta_id AND s.cgsc_id = a.sct_id
WHERE g.ger_id = 1
GROUP BY g.ger_id, p.cgp_id, r.rub_id, c.cgcu_id;
I have no idea why it gives me this error, i'm new in sql.
you just need to add all the columns in GROUP BY which are present in the SELECT statement.
Seems like simple aggregation here. I cleaned up the code and added some columns to the GROUP BY.
SELECT
id = c.cgcu_cuenta
,g.ger_cuenta
,g.ger_nombre
,p.cgp_cuenta
,p.cgp_nombre
,r.rub_cuenta
,r.rub_nombre
,c.cgcu_cuenta
,c.cgcu_nombre
,s.cgsc_cuenta
,s.cgsc_nombre
,debe = SUM(IFNULL(a.debe, 0)) - SUM(IFNULL(a.haber, 0))
,haber = 0
,nat_id = 'D'
,cuenta = c.cgcu_cuenta
,nombre = c.cgcu_nombre
FROM ctrl2019.cat_Genero g
INNER JOIN ctrl2019.cat_CgGrupo p ON USING(ger_id)
INNER JOIN ctrl2019.cat_Rubro r ON USING(ger_id, cgp_id)
INNER JOIN ctrl2019.cat_CgCuenta c USING(ger_id, cgp_id, rub_id)
INNER JOIN ctrl2019.cat_CgSubcuenta s USING(ger_id, cgp_id, rub_id, cgcu_id)
LEFT JOIN (
SELECT
a2.ger_id
,a2.grp_id
,a2.rub_id
,a2.cta_id
,a2.sct_id
,debe = SUM(IFNULL(a2.msl_debe, 0))
,haber = SUM(IFNULL(a2.msl_haber, 0))
FROM ldf.vin_EntePublicoLDF E
INNER JOIN ldf.blz_Mensual_2019 a2 USING(gpo_id, ur_id)
WHERE e.ejr_id = 2019
AND a2.ger_id = 1
AND e.ent_id = 12
AND a2.msc_id IN (0, 1, 2, 3)
GROUP BY
a2.ger_id
,a2.grp_id
,a2.rub_id
,a2.cta_id
,a2.sct_id
) A
ON s.ger_id = A.ger_id
AND s.cgp_id = A.grp_id
AND s.rub_id = A.rub_id
AND s.cgcu_id = A.cta_id
AND s.cgsc_id = A.sct_id
WHERE g.ger_id = 1
GROUP BY
g.ger_id
,p.cgp_id
,r.rub_id
,C.cgcu_id
,c.cgcu_cuenta
,g.ger_cuenta
,g.ger_nombre
,p.cgp_cuenta
,p.cgp_nombre
,r.rub_cuenta
,r.rub_nombre
,c.cgcu_nombre
,s.cgsc_cuenta
,s.cgsc_nombre
I am trying to fetch the results from the DB using the Entity Framework using the below SQL query:
SELECT
Header_Id,
Header_Number, Details_Id,
Details_Header_Date,
(SELECT TOP 1 c.[Comment_Description] FROM [Comment] c
WHERE c.[Comment_CarrierId] = i.[Header_CarrierId] AND c.[Comment_ParentEntityId] = i.[Header_Id]
ORDER BY c.Comment_AddedOn DESC) AS 'HeaderComments',
CONCAT(ht.[HeaderTracker_Reason], ' ', ht.[HeaderTracker_Notes]) AS 'RejectedComments',
at.[InternalComments] AS 'InternalComments',
CASE i.[Header_Status]
WHEN 'Pending' THEN ar.[HeaderTracker_ApprovedLvl] END AS 'ApprovedLevel',
CASE i.[Header_Status]
WHEN 'Pending' THEN ar.[HeaderTracker_DueBy] END AS 'ApprovedDueDate'
FROM [Header] i
LEFT OUTER JOIN [Details] ii
ON i.[Header_Id] = ii.[Details_HeaderId]
INNER JOIN [Carrier] t
ON t.[Carrier_Id] = i.[Header_CarrierId]
LEFT OUTER JOIN [HeaderTracker] ht
ON ht.[HeaderTracker_HeaderId] = i.[Header_Id] AND ht.[HeaderTracker_Type] = 'Rejected'
LEFT OUTER JOIN [AdjustmentTracker] at
ON at.[DetailsId] = ii.[Details_Id]
LEFT OUTER JOIN [HeaderTracker] ar
ON ar.[HeaderTracker_HeaderId] = i.[Header_Id]
AND i.[Header_Status] IN ('Paid', 'Pending', 'Approved', 'PaidWithAdj')
AND ar.[HeaderTracker_IsPending] = 1
The result output should be using LINQ query / LAMBDA expression
The following code is what I tried: (not sure how TOP 1 and CASE would come here + if & is also valid here)
var statuses = new string[] { "Paid", "Pending", "Approved", "PaidWithAdj" };
var hdrdet =
(
from hdr in dbContext.Headers
join det in dbContext.Details on hdr.Header_Id equals det.Header_Id into hdrdet
from h in hdrdet.DefaultIfEmpty()
join carr in dbContext.Carriers on hdr.Carrier_Id equals carr.Header_Carrier_Id into carrs
from c in carrs.DefaultIfEmpty()
join hdrtk in dbContext.HeaderTracker on hdr.Header_Id equals hdrtk.HeaderTracker_HeaderId && hdrtk.HeaderTracker_Type equals "Rejected" into hdrtks
from k in hdrtks.DefaultIfEmpty()
join adjt in dbContext.AdjustmentTracker on adjt.DetailsId equals det.Details_Id into adjts
from a in adjts.DefaultIfEmpty()
join pnd in dbContext.HeaderTracker on pnd.HeaderTracker_HeaderId equals hdr.Header_Id && hdr.Header_Status contains(statuses) && pnd.[HeaderTracker_IsPending] equals 1 into pnds
from p in pnds.DefaultIfEmpty()
select new
{
hdrid = Header_Id,
hdrnumber = Header_Number, Details_Id,
det_date = Details_Header_Date,
reason = HeaderTracker_Reason + ' ' + HeaderTracker_Notes,
intcomments = InternalComments
}
)
I have a SQL query that takes a subquery as a parameter for a left join.
SELECT tblfLeaseDetail.Lease_Detail_ID,
tblfPayment.Payment_Date,
tblfAuthorization.Authorized,
tblvVendor.Vendor_Name,
tblvCounty.County
FROM tblfLeaseDetail
LEFT
JOIN tblfPayment
ON tblfPayment.Lease_Detail_ID = tblfLeaseDetail.Lease_Detail_ID
AND tblfPayment.Payment_ID =
( SELECT TOP 1
Payment_ID
FROM tblfPayment
WHERE tblfPayment.Lease_Detail_ID = tblfLeaseDetail.Lease_Detail_ID
ORDER BY Payment_Date DESC
)
LEFT
JOIN tblfAuthorization
ON tblfAuthorization.Lease_Detail_ID = tblfLeaseDetail.Lease_Detail_ID
AND tblfAuthorization.Authorization_ID =
( SELECT TOP 1
Authorization_ID
FROM tblfAuthorization
WHERE tblfAuthorization.Lease_Detail_ID = tblfLeaseDetail.Lease_Detail_ID
ORDER BY Authorized_Date DESC
)
LEFT JOIN tblvVendor
on tblvVendor.Vendor_ID = tblfLeaseDetail.Vendor_ID
LEFT JOIN tblvCounty
on tblvCounty.County_ID = tblfLeaseDetail.County_ID
I'm trying to convert it to LINQ. So far this is what I've done:
var leaseList = (from l in leases.tblfLeaseDetails
join a in leases.tblfAuthorizations on l.Lease_Detail_ID equals a.Lease_Detail_ID into la
from jla in
(from aj in leases.tblfAuthorizations
where aj.Lease_Detail_ID == l.Lease_Detail_ID
orderby aj.Authorized_Date descending
select aj.Authorization_ID).Take(1).DefaultIfEmpty()
join p in leases.tblfPayments on l.Lease_Detail_ID equals p.Lease_Detail_ID into lp
from jlp in
(from pj in leases.tblfPayments
where pj.Lease_Detail_ID == l.Lease_Detail_ID
orderby pj.Payment_Date descending
select pj.Payment_ID).Take(1).DefaultIfEmpty()
join v in leases.tblvVendors on l.Vendor_ID equals v.Vendor_ID into lv
from jlv in lv.DefaultIfEmpty()
join c in leases.tblvCounties on l.County_ID equals c.County_ID into lc
from jlc in lc.DefaultIfEmpty()
select new LeaseViewModel()
{
Lease_Detail_ID = l.Lease_Detail_ID,
Vendor_Name = jlv.Vendor_Name,
County = jlc.County,
Authorization = jla.Authorized,
Payment_Date = jlp.Payment_Date
}).Distinct()
This returns me an error at jla.Authorized and jlp.Payment_Date:
'int' does not contain a definition for 'Authorized' and no extension method 'Authorized' accepting a first argument of type 'int' could be found
The same error goes for Payment_Date.
Why are jla and jlp being considered ints? How can I make this query work?
EDIT:
This is the final and working LINQ query:
var leaseList = (from l in leases.tblfLeaseDetails
join a in leases.tblfAuthorizations on l.Lease_Detail_ID equals a.Lease_Detail_ID into la
from jla in la.DefaultIfEmpty()
where jla.Authorization_ID == (from aj in leases.tblfAuthorizations
where aj.Lease_Detail_ID == l.Lease_Detail_ID
orderby aj.Authorized_Date descending
select aj.Authorization_ID).Take(1).FirstOrDefault()
join p in leases.tblfPayments on l.Lease_Detail_ID equals p.Lease_Detail_ID into lp
from jlp in lp.DefaultIfEmpty()
where jlp.Payment_ID == (from pj in leases.tblfPayments
where pj.Lease_Detail_ID == l.Lease_Detail_ID
orderby pj.Payment_Date descending
select pj.Payment_ID).Take(1).FirstOrDefault()
join v in leases.tblvVendors on l.Vendor_ID equals v.Vendor_ID into lv
from jlv in lv.DefaultIfEmpty()
join c in leases.tblvCounties on l.County_ID equals c.County_ID into lc
from jlc in lc.DefaultIfEmpty()
select new LeaseViewModel()
{
Lease_Detail_ID = l.Lease_Detail_ID,
Lease_ID = l.Lease_ID,
XRef_Lease_ID = l.XRef_Lease_ID,
Vendor_Name = jlv.Vendor_Name,
Description = l.Description,
County = jlc.County,
Amount = l.Amount,
Payment_Due_Date = l.Payment_Due_Date,
Lease_Type = l.Lease_Type.ToString(),
Location_ID = l.Location_ID,
Active = l.Active,
Expiration_Date = l.Expiration_Date,
Authorization = jla.Authorized,
Payment_Date = jlp.Payment_Date
}).Distinct();
That is because you are selecting Authorization_ID and Payment_ID which are of type int into jla and jlp respectively . Try the below query and let me know how it worked for you.
var leaseList = (from l in leases.tblfLeaseDetails
join a in leases.tblfAuthorizations on l.Lease_Detail_ID equals a.Lease_Detail_ID into la
from jla in
(from aj in leases.tblfAuthorizations
where aj.Lease_Detail_ID == l.Lease_Detail_ID
orderby aj.Authorized_Date descending
select aj).Take(1).DefaultIfEmpty()
join p in leases.tblfPayments on l.Lease_Detail_ID equals p.Lease_Detail_ID into lp
from jlp in
(from pj in leases.tblfPayments
where pj.Lease_Detail_ID == l.Lease_Detail_ID
orderby pj.Payment_Date descending
select pj).Take(1).DefaultIfEmpty()
join v in leases.tblvVendors on l.Vendor_ID equals v.Vendor_ID into lv
from jlv in lv.DefaultIfEmpty()
join c in leases.tblvCounties on l.County_ID equals c.County_ID into lc
from jlc in lc.DefaultIfEmpty()
select new LeaseViewModel()
{
Lease_Detail_ID = l.Lease_Detail_ID,
Vendor_Name = jlv.Vendor_Name,
County = jlc.County,
Authorization = jla.Authorized,
Payment_Date = jlp.Payment_Date
}).Distinct()
How do I write this query in linq VB.NET?
select top 15 count(1), A.Latitude, A.Longitude
from Bairro A
inner join Empresa B on B.BairroID = A.BairroID
where A.CidadeID = 4810
group by A.Latitude, A.Longitude
order by COUNT(1) desc
I reached this code:
Dim TopBairros = (From A In Bairros _
Join B In New BO.Empresa().Select On B.BairroID Equals A.BairroID Group A By A.Latitude, A.Longitude Into g = Group _
Select g Distinct _
Order By g.Count Descending).Take(15)
Each row has a array collection containing repeatly the same objects with the count number. Example:
row 0: array of 874 same objects
row 1: array of 710 same objects
and so on... How do I do to return only ONE object per row?
Try this:
var query = from a in context.Bairro
where a.CidadeID == 4810
join b in context.Empresa on a.BairroID equals b.BairroID
group a by new { a.Latitude, a.Longitude } into grouped
orderby grouped.Count() descending
select new { grouped.Key.Latitude,
grouped.Key.Longitude,
Count = grouped.Count() };
var top15 = query.Take(15);