Error 1055 SQL - SELECT list is not in GROUP BY - sql

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

Related

SQL to Linq - NET CORE 5

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]

Convert SQL Query to LINQ query/Lambda expression

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

How to avoid union all

Any possibility methods to avoiding "Union all" when different joining > conditions varies on each section
SELECT RS1.*, EXL.*
FROM "EXL" "EXL"
INNER JOIN "RS1" "RS1"
ON "RS1"."HEADER_KEY" = "EXL"."HEADER_KEY"
WHERE "RS1"."PIPE_KEY" = '1109' AND
"RS1"."COLK" IS NULL AND
"RS1".CT1 = 0 AND "RS1".CT2 > 0
UNION ALL
SELECT RS1.*, EXL.*
FROM "EXL" "EXL"
INNER JOIN "RS1" "RS1"
ON "RS1"."HEADER_KEY" = "EXL"."HEADER_KEY"
INNER JOIN "YFS"."STATUS_MAP" "SOS"
ON "SOS"."STATUS" = "RS1"."STATUS"
INNER JOIN "RS1" "RS2"
ON "RS2"."LINE_KEY" = "RS1"."CHAINLINE_KEY" AND
"RS2"."PIPEKEY" = "SOS"."TYPE_KEY" AND
"RS2"."STATUS" = "SOS"."EXTN_STATUS" AND
"RS2"."PIPE_KEY" = '4093'
WHERE "RS1"."PIPE_KEY" = '1109' AND
"RS1"."COLK" IS NULL AND
"RS1".CT1 = 0 AND "RS1".CT2 > 0
Since the two SELECTs have exactly the same WHERE-condition, I assume that you want to return rows from EXL, even when rows from YFS.STATUS_MAP are missing (otherwise please explain what your intention is). You can do this with LEFT JOIN
SELECT RS1.*, EXL.*
FROM
"EXL"
INNER JOIN "RS1"
ON "RS1"."HEADER_KEY" = "EXL"."HEADER_KEY"
LEFT JOIN "YFS"."STATUS_MAP" "SOS"
ON "SOS"."STATUS" = "RS1"."STATUS"
LEFT JOIN "RS1" "RS2"
ON "RS2"."LINE_KEY" = "RS1"."CHAIN_LINE_KEY" AND
"RS2"."PIPEKEY" = "SOS"."TYPE_KEY" AND
"RS2"."STATUS" = "SOS"."EXTN_STATUS" AND
"RS2"."PIPELINE_KEY" = '4093'
WHERE "RS1"."PIPELINE_KEY" = '1109' AND
"RS1"."COLK" IS NULL AND
"RS1".CT1 = 0 AND "RS1".CT2 > 0

Convert to linq sql query error

I have a query according to the :
SELECT
tblDefinition.TopsisType, tblTemplate.tType, tblEvaluationFormCategory.Title AS EvaluationCategory,
CASE tType WHEN 1 THEN N'2'
ELSE N'1' END ProcessType,
tblDefinition.Description, tblDefinition.TemplateID, 1 Destinition
FROM tblTemplate INNER JOIN
tblEvaluationFormCategory ON tblTemplate.CategoryID = tblEvaluationFormCategory.ID INNER JOIN
tblEFQMAlternative INNER JOIN
tblDefinition ON ([tblEFQMAlternative].[TopsisID] = [tblDefinition].[TopsisID] AND [tblEFQMAlternative].[CustomerID] = [tblDefinition].[CustomerID]) INNER JOIN
tblGroupMembers ON ([tblDefinition].[TopsisID] = [tblGroupMembers].[TopsisID]
AND tblDefinition.CustomerID =
tblGroupMembers.CustomerID) ON tblTemplate.TemplateID = tblDefinition.TemplateID
INNER JOIN
tblTerm ON tblDefinition.TermGrant = tblTerm.Title
WHERE (tblTerm.ID = 20) AND (tblGroupMembers.UserID = 558)
GROUP BY tblDefinition.TopsisType, tblTemplate.tType, tblEvaluationFormCategory.Title,
tblDefinition.Description, tblDefinition.TemplateID
when i convert to linq, then error to :
Field [([tblDefinition].[TopsisID] = [tblGroupMembers]].[[TopsisID] AND tblDefinition.CustomerID = tblGroupMembers.CustomerID) ON tblTemplate.TemplateID] not found in the current Data Context.
What should I do?

SQL UPDATE using two joined subqueries

I wrote a query that does an inner join of two subqueries. The first subquery has an alias of "SRC" and the other has an alias of "DEST". What I want to do is update some fields in the table NomineeActionLegislatorVoteDetail (part of DEST subquery) with values from the table Nominee_Committee_Vote (part of SRC subquery). It souds easy but I just cannot figure out how to do it. Does anyone have any suggestions? Any help would be appreciated.
Here is the query I wrote:
select *
from (
select ncv.*,
na.NomineeActionId,
l.LegislatorId
from ongoing..Nominee_Committee_Vote ncv
inner join azleg..NomineeAction na on
ncv.session_id = na.x_session_id and
ncv.committee_id = na.x_committee_id and
ncv.agency_id = na.x_agency_id and
ncv.position_id = na.x_position_id and
ncv.nominee_id = na.x_nominee_id and
ncv.received_date = na.x_received_date
inner join status..session s on
ncv.session_id = s.session_id
inner join azleg..Legislator l on
ncv.member_id = l.x_member_id and
s.legislature = l.LegislatureId
) SRC
inner join (
select votedetail.*
from azleg..NomineeActionLegislatorVoteDetail votedetail
inner join azleg..NomineeAction nom_action on
votedetail.NomineeActionId = nom_action.NomineeActionId
) DEST on
SRC.agency_id = DEST.x_agency_id and
SRC.position_id = DEST.x_position_id and
SRC.nominee_id = DEST.x_nominee_id and
SRC.received_date = DEST.x_received_date and
SRC.session_id = DEST.x_session_id and
SRC.committee_id = DEST.x_committee_id and
SRC.member_id = DEST.x_member_id
where SRC.NomineeActionId <> DEST.NomineeActionId
OR SRC.LegislatorId <> DEST.LegislatorId
OR SRC.Vote <> DEST.Vote
Can you insert the update in front of the sub queries
UPDATE NomineeActionLegislatorVoteDetail
SET NomineeActionLegislatorVoteDetail.COLUMNNAME = src.VALUE
--SubQueriesBelow
from
(select ncv.*, na.NomineeActionId, l.LegislatorId from ongoing..Nominee_Committee_Vote ncv
inner join azleg..NomineeAction na on
ncv.session_id = na.x_session_id and
ncv.committee_id = na.x_committee_id and
ncv.agency_id = na.x_agency_id and
ncv.position_id = na.x_position_id and
ncv.nominee_id = na.x_nominee_id and
ncv.received_date = na.x_received_date
inner join status..session s on
ncv.session_id = s.session_id
inner join azleg..Legislator l on
ncv.member_id = l.x_member_id and
s.legislature = l.LegislatureId) SRC
inner join
(select votedetail.* from azleg..NomineeActionLegislatorVoteDetail votedetail
inner join azleg..NomineeAction nom_action on
votedetail.NomineeActionId = nom_action.NomineeActionId) DEST on
SRC.agency_id = DEST.x_agency_id and
SRC.position_id = DEST.x_position_id and
SRC.nominee_id = DEST.x_nominee_id and
SRC.received_date = DEST.x_received_date and
SRC.session_id = DEST.x_session_id and
SRC.committee_id = DEST.x_committee_id and
SRC.member_id = DEST.x_member_id
where SRC.NomineeActionId <> DEST.NomineeActionId
OR SRC.LegislatorId <> DEST.LegislatorId
OR SRC.Vote <> DEST.Vote
It looks like the update is on a table in the sub query so it could be re factored to have one subquery
I've adjusted the lay-out of your query a bit to disclose better where subqueries start and end. In your DEST subquery, you join NomineeAction but you don't select any columns from it, so it only filters rows from NomineeActionLegislatorVoteDetail for which no NomineeAction exists. So really you wanna be updating and joining on columns from NomineeActionLegislatorVoteDetail exclusively. Based on that, I would write the update query like so:
update votedetail set
votedetail.SomeColumn = SomeValue,
votedetail.SomeOtherColumn = SomeOtherValue
from azleg..NomineeActionLegislatorVoteDetail votedetail
join azleg..NomineeAction nom_action on
votedetail.NomineeActionId = nom_action.NomineeActionId
join (
select ncv.*,
na.NomineeActionId,
l.LegislatorId
from ongoing..Nominee_Committee_Vote ncv
inner join azleg..NomineeAction na on
ncv.session_id = na.x_session_id and
ncv.committee_id = na.x_committee_id and
ncv.agency_id = na.x_agency_id and
ncv.position_id = na.x_position_id and
ncv.nominee_id = na.x_nominee_id and
ncv.received_date = na.x_received_date
inner join status..session s on
ncv.session_id = s.session_id
inner join azleg..Legislator l on
ncv.member_id = l.x_member_id and
s.legislature = l.LegislatureId
) SRC on
SRC.agency_id = votedetail.x_agency_id and
SRC.position_id = votedetail.x_position_id and
SRC.nominee_id = votedetail.x_nominee_id and
SRC.received_date = votedetail.x_received_date and
SRC.session_id = votedetail.x_session_id and
SRC.committee_id = votedetail.x_committee_id and
SRC.member_id = votedetail.x_member_id
where SRC.NomineeActionId <> votedetail.NomineeActionId
OR SRC.LegislatorId <> votedetail.LegislatorId
OR SRC.Vote <> votedetail.Vote