summation in sql - sql

I have a query result tabletable of result i would like to sum the bill amount such that it returns one row with a distinct account ,balance,sum billed amount fPreviousReading,
fCurrentReading,
fConsumption .
result should be
1.account 11074
2.balance269.49
3.sumbilledamount 520.48
4. fPreviousReading 574
5 fCurrentReading 612
6 fConsumption 38
Thanks
query
select
Ten.Account,
ten.DCBalance AS Balance,
SUM(T.fInclusiveAmount)AS BilledAmount,
MRD.fPreviousReading,
MRD.fCurrentReading ,
MRD.fConsumption ,
T.cDescription
from _mtblTransactions T
left join _mtblProperties P ON P.idProperty = T.iPropertyID
left join _mtblPropertyPortions PP ON PP.idPropertyPortions = T.iPortionID
left join _mtblPropertyPortionServices PPS ON PPS.idPropertyPortionServices = T.iPropertyPortionServiceID
left join _mtblCategories Cat ON Cat.idCategory = PP.iPortionUsageID
left join _mtblServices S ON PPS.iPortionServiceID = S.idService
left join _mtblServiceGroups SG ON S.iServiceGroupID = SG.idServiceGroup
left join _mtblRateTariffs RT ON RT.idRateTariffs = PPS.iServiceRateTariffID
left join Client Ten ON T.iCustomerID = Ten.DCLink
left join _mtblMeters M ON PPS.iPropertyPortionMeterID = M.idMeter
left join _mtblWalkDetails WD ON WD.iWalkMeterID = PPS.iPropertyPortionMeterID
left join _mtblWalks W ON WD.iWalkID = W.idWalk
left join Client Own ON P.iPropertyOwnerID = Own.DCLink
left outer join _mtblRegions R on R.idRegions = P.iPropertyRegionID
left outer join _mtblSubRegions SR on SR.idSubRegions = P.iPropertySubRegionID
left outer join _mtblAreas A on A.idAreas = P.iPropertyAreaID
left join _etblPeriod PER ON T.iPeriodID = PER.idPeriod
left join _mtblMeterReadingDetails MRD ON T.iMeterID = MRD.iMeterReadingsMeterID and T.iPeriodID = MRD.iBillingPeriodID
and MRD.iReadingType=0
Where
oWN.Account='11074'
and idPeriod='79'
GROUP BY Ten.Account,ten.DCBalance,MRD.fPreviousReading, MRD.fCurrentReading, MRD.fConsumption, T.cDescription

As I don't know your data, there is a possibility I wrote you a code that would return some double rows. But that is a problem you can easily handle.
Try it, nevertheless:
SELECT t1.Account,
t1.Balance,
t1.BilledAmount,
t1.fPreviousReading,
t1.fCurrentReading,
t1.fConsumption,
t2.cDescription
FROM (SELECT Ten.Account,
ten.DCBalance AS Balance,
SUM (T.fInclusiveAmount) AS BilledAmount,
SUM (MRD.fPreviousReading) AS fPreviousReading,
SUM (MRD.fCurrentReading) AS fCurrentReading,
SUM (MRD.fConsumption) AS fConsumption
FROM _mtblTransactions T
left join _mtblProperties P ON P.idProperty = T.iPropertyID
left join Client Ten ON T.iCustomerID = Ten.DCLink
left join Client Own ON P.iPropertyOwnerID = Own.DCLink AND oWN.Account='11074'
left join _etblPeriod PER ON T.iPeriodID = PER.idPeriod
left join _mtblMeterReadingDetails MRD ON T.iMeterID = MRD.iMeterReadingsMeterID and T.iPeriodID = MRD.iBillingPeriodID
and MRD.iReadingType=0
and idPeriod='79'
GROUP BY Ten.Account,ten.DCBalance) t1
JOIN (SELECT T.cDescription,
Ten.Account,
ten.DCBalance
FROM _mtblTransactions T
left join Client Ten ON T.iCustomerID = Ten.DCLink) t2 ON t2.Account = t1.Account AND t2.DCBalance = t1.DCBalance

Related

Best Join Strategy/Indexes for SQL Server

What is the best join strategy/indexes for this query:
SELECT
kwk.*, an.AuftragDatum, an.AbgabeDatum, an.BezahltDatum, an.AuftragStatus
FROM
KundenWerbenKunden kwk
INNER JOIN
Auftrag an ON an.AuftragNummer = kwk.AuftragNummer
WHERE
kwk.Deleted = 0
Table KundenWerbenKunden has 103950 rows with 103646 Deleted = 0 ones.
Table Auftrag has 3826552 rows.
In my real query I make some more joins:
INNER JOIN
Filiale fn WITH (NOLOCK) ON an.FilialeID = fn.FilialeID
INNER JOIN
Kunde kn ON an.KundeID = kn.KundeID
OUTER APPLY
(SELECT DISTINCT KSKNr
FROM KdZuordnung
WHERE KundeID = kn.KundeID) zn
LEFT JOIN
Anrede ann WITH (NOLOCK) ON kn.Anrede = ann.Anrede
INNER JOIN
AuftragArt aa WITH (NOLOCK) ON an.AuftragArtID = aa.AuftragArtID
INNER JOIN
AuftragGrund ag WITH (NOLOCK) ON an.AuftragGrundID = ag.AuftragGrundID
INNER JOIN
AuftragType at WITH (NOLOCK) ON an.AuftragTypeID = at.AuftragTypeID
For this query:
SELECT *
FROM KundenWerbenKunden kwk INNER JOIN
Auftrag an
ON an.AuftragNummer = kwk.AuftragNummer
WHERE kwk.Geloescht = 0;
And not knowing anything about the distribution of Geloescht, I would first try indexes on KundenWerbenKunden(Geloescht, AuftragNummer) and Auftrag(AuftragNummer).

How to get rid of duplicating data in every row?

SELECT distinct AD.ReferenceNumber, AD.ProjectTitle, Z.ZoneCode, C.CompanyName,SS.AssignedTo, ZG.ZoneGroupName,au.Amount
FROM ApplicationDetails AD
LEFT JOIN ApplicationFormsDetails AS b ON (AD.referencenumber = b.referencenumber)
LEFT JOIN ScheduleSummaries AS SS ON (AD.ReferenceNumber = SS.ReferenceNo)
INNER JOIN AppTypes as at on ss.ItemCode = at.Category
INNER JOIN Companies AS C ON (AD.CompanyId = C.CompanyID)
INNER JOIN Zones Z ON (C.ZoneCode = Z.ZoneCode)
INNER JOIN ZoneGroups ZG ON (Z.ZoneGroup = ZG.ZoneGroupId)
LEFT JOIN AssessmentUsedItems au on ah.AssessmentHeaderId = au.HeaderId
WHERE AD.ApplicationDate BETWEEN '2017-10-01' AND '2017-10-31' AND ZG.ZoneGroupCode = 'HO' and ah.referencenumber = 'N-101317-A1-02'
GROUP BY AD.ReferenceNumber, AD.ProjectTitle, Z.ZoneCode, C.CompanyName,SS.AssignedTo, ZG.ZoneGroupName,au.Amount--, ah.ApplicationForm,au.Amount
The output of this query is its duplicating the amount for every AssignTO.
Output :
Maybe you want to try using SUM(ISNULL(au.amount, 0)) AS amount instead of au.amount and remove au.amount from the GROUP BY as well...
Try this query:
SELECT AD.ReferenceNumber,
AD.ProjectTitle,
Z.ZoneCode,
C.CompanyName,
SS.AssignedTo,
ZG.ZoneGroupName,
SUM(COALESCE(au.Amount,0)) AS Amount
FROM ApplicationDetails AD
LEFT JOIN ApplicationFormsDetails AS b
ON (AD.referencenumber = b.referencenumber)
LEFT JOIN ScheduleSummaries AS SS
ON (AD.ReferenceNumber = SS.ReferenceNo)
INNER JOIN AppTypes AS at
ON ss.ItemCode = at.Category
INNER JOIN Companies AS C
ON (AD.CompanyId = C.CompanyID)
INNER JOIN Zones Z
ON (C.ZoneCode = Z.ZoneCode)
INNER JOIN ZoneGroups ZG
ON (Z.ZoneGroup = ZG.ZoneGroupId)
LEFT JOIN AssessmentUsedItems au
ON ah.AssessmentHeaderId = au.HeaderId
WHERE AD.ApplicationDate BETWEEN '2017-10-01' AND '2017-10-31'
AND ZG.ZoneGroupCode = 'HO'
AND ah.referencenumber = 'N-101317-A1-02'
GROUP BY
AD.ReferenceNumber,
AD.ProjectTitle,
Z.ZoneCode,
C.CompanyName,
SS.AssignedTo,
ZG.ZoneGroupName

SQL Case statement with multi left outer joins

Is it possible to do case statements and to left outer joins like I am doing below? I put comments on what I am trying to achieve.
SELECT
eventGame.Id,
eventGame.[Type] AS GameType
FROM GrassrootsHoops.EventGame eventGame
LEFT OUTER JOIN (SELECT
divisionGameTeamResult.Id,
divisionGameTeamResult.GameId,
COALESCE(divisionPool.Name, divisionTeamPoolPoolBracket.Name) AS DivisionPoolName
FROM GrassrootsHoops.DivisionGameTeamResult divisionGameTeamResult
LEFT OUTER JOIN
-- CASE eventGame.[Type] = 1 THEN
GrassrootsHoops.DivisionTeamPoolGame divisionTeamPoolGame
ON divisionTeamPoolGame.Id = divisionGameTeamResult.Id
LEFT OUTER JOIN GrassrootsHoopS.DivisionTeamPool divisionTeamPool
ON divisionTeamPool.Id = divisionTeamPoolGame.DivisionTeamPoolId
LEFT OUTER JOIN GrassrootsHoops.DivisionPool divisionPool
ON divisionPool.Id = divisionTeamPool.DivisionPoolId
LEFT OUTER JOIN GrassrootsHoops.DivisionPoolSettings divisionPoolSettings
ON divisionPool.Id = divisionPoolSettings.Id
LEFT OUTER JOIN GrassrootsHoops.DivisionTeam divisionTeam
ON divisionTeam.Id = divisionTeamPool.DivisionTeamId
LEFT OUTER JOIN GrassrootsHoops.Team team
ON team.Id = divisionTeam.Id
LEFT OUTER JOIN
-- CASE eventGame.[Type] = 2 THEN
GrassrootsHoops.DivisionBracketParticipant divisionBracketGameParticipant
ON divisionBracketGameParticipant.DivisionGameTeamResultId = divisionGameTeamResult.Id
LEFT OUTER JOIN GrassrootsHoops.DivisionBracketParticipantPart divisionBracketParticipantPart
ON divisionBracketParticipantPart.Id = divisionBracketGameParticipant.DivisionBracketParticipantPartId
LEFT OUTER JOIN GrassrootsHoops.DivisionBracketParticipantTeam divisionBracketGameParticipantTeam
ON divisionBracketGameParticipantTeam.Id = divisionBracketGameParticipant.Id
LEFT OUTER JOIN GrassrootsHoops.DivisionTeam divisionTeamBracket
ON divisionTeamBracket.Id = divisionBracketGameParticipantTeam.DivisionTeamId
LEFT OUTER JOIN GrassrootsHoops.Team teamBracket
ON teamBracket.Id = divisionTeamBracket.Id
LEFT OUTER JOIN GrassrootsHoops.DivisionBracketParticipantBracket divisionBracketParticipantBracket
ON divisionBracketParticipantBracket.Id = divisionBracketGameParticipant.Id
LEFT OUTER JOIN GrassrootsHoops.DivisionBracket divisionBracketParticipantBracketBracket
ON divisionBracketParticipantBracketBracket.Id = divisionBracketParticipantBracket.DivisionBracketId
LEFT OUTER JOIN GrassrootsHoops.DivisionBracketParticipantPool divisionBracketGameParticipantPool
ON divisionBracketGameParticipantPool.Id = divisionBracketGameParticipant.Id
LEFT OUTER JOIN GrassrootsHoops.DivisionPool divisionPoolBracket
ON divisionPoolBracket.Id = divisionBracketGameParticipantPool.DivisionPoolId
LEFT OUTER JOIN GrassrootsHoops.DivisionBracketParticipantTeamPool divisionBracketGameParticipantTeamPool
ON divisionBracketGameParticipantTeamPool.Id = divisionBracketGameParticipant.Id
LEFT OUTER JOIN GrassrootsHoops.DivisionTeamPool divisionTeamPoolBracket
ON divisionTeamPoolBracket.Id = divisionBracketGameParticipantTeamPool.DivisionTeamPoolId
LEFT OUTER JOIN GrassrootsHoops.DivisionPool divisionTeamPoolPoolBracket
ON divisionTeamPoolPoolBracket.Id = divisionTeamPoolBracket.DivisionPoolId
LEFT OUTER JOIN GrassrootsHoops.DivisionTeam divisionTeamPoolTeamBracket
ON divisionTeamPoolTeamBracket.Id = divisionTeamPoolBracket.DivisionTeamId
LEFT OUTER JOIN GrassrootsHoops.Team teamPoolTeamBracket
ON teamPoolTeamBracket.Id = divisionTeamPoolTeamBracket.Id
WHERE divisionGameTeamResult.HomeTeam = 1) homeTeam
ON homeTeam.GameId = eventGame.GameId
You can't do case statements with outer joins. I think you can do what you want, though by using a UNION. Here's an example using a simpler schema where we are doing two separate joins based on the type of game.
SELECT
Game.Id,
PoolResult.Score
FROM
Game
JOIN PoolResult
ON PoolResult.GameId = Game.Id
WHERE
Game.GameType = 1
UNION
SELECT
Game.Id,
BracketResult.Score
FROM
Game
JOIN BracketResult
ON BracketResult.GameId = Game.Id
WHERE
Game.GameType = 2
(Here's a working version at SQL Fiddle)
For your query, you just want to write two completely separate queries one for each type of game. Once you have that working for each separate query, just stick a UNION in between them and the results will be concatenated together. Here's your query modified to use a UNION. I don't have an easy way to check it for errors, so there's probably some minor errors
SELECT
divisionGameTeamResult.Id,
eventGame.[Type] AS GameType
FROM
GrassrootsHoops.EventGame eventGame
JOIN GrassrootsHoops.DivisionGameTeamResult divisionGameTeamResult
ON (divisionGameTeamResult.GameId = eventGame.GameId
JOIN GrassrootsHoops.DivisionTeamPoolGame divisionTeamPoolGame
ON divisionTeamPoolGame.Id = divisionGameTeamResult.Id
JOIN GrassrootsHoopS.DivisionTeamPool divisionTeamPool
ON divisionTeamPool.Id = divisionTeamPoolGame.DivisionTeamPoolId
JOIN GrassrootsHoops.DivisionPool divisionPool
ON divisionPool.Id = divisionTeamPool.DivisionPoolId
JOIN GrassrootsHoops.DivisionPoolSettings divisionPoolSettings
ON divisionPool.Id = divisionPoolSettings.Id
JOIN GrassrootsHoops.DivisionTeam divisionTeam
ON divisionTeam.Id = divisionTeamPool.DivisionTeamId
JOIN GrassrootsHoops.Team team
ON team.Id = divisionTeam.Id
WHERE
divisionGameTeamResult.HomeTeam = 1
AND
eventGame.[Type] = 1
UNION
SELECT
divisionGameTeamResult.Id,
eventGame.[Type] AS GameType
FROM
GrassrootsHoops.EventGame eventGame
JOIN GrassrootsHoops.DivisionGameTeamResult divisionGameTeamResult
ON (divisionGameTeamResult.GameId = eventGame.GameId)
JOIN GrassrootsHoops.DivisionBracketParticipant divisionBracketGameParticipant
ON divisionBracketGameParticipant.DivisionGameTeamResultId = divisionGameTeamResult.Id
JOIN GrassrootsHoops.DivisionBracketParticipantPart divisionBracketParticipantPart
ON divisionBracketParticipantPart.Id = divisionBracketGameParticipant.DivisionBracketParticipantPartId
JOIN GrassrootsHoops.DivisionBracketParticipantTeam divisionBracketGameParticipantTeam
ON divisionBracketGameParticipantTeam.Id = divisionBracketGameParticipant.Id
JOIN GrassrootsHoops.DivisionTeam divisionTeamBracket
ON divisionTeamBracket.Id = divisionBracketGameParticipantTeam.DivisionTeamId
JOIN GrassrootsHoops.Team teamBracket
ON teamBracket.Id = divisionTeamBracket.Id
JOIN GrassrootsHoops.DivisionBracketParticipantBracket divisionBracketParticipantBracket
ON divisionBracketParticipantBracket.Id = divisionBracketGameParticipant.Id
JOIN GrassrootsHoops.DivisionBracket divisionBracketParticipantBracketBracket
ON divisionBracketParticipantBracketBracket.Id = divisionBracketParticipantBracket.DivisionBracketId
JOIN GrassrootsHoops.DivisionBracketParticipantPool divisionBracketGameParticipantPool
ON divisionBracketGameParticipantPool.Id = divisionBracketGameParticipant.Id
JOIN GrassrootsHoops.DivisionPool divisionPoolBracket
ON divisionPoolBracket.Id = divisionBracketGameParticipantPool.DivisionPoolId
JOIN GrassrootsHoops.DivisionBracketParticipantTeamPool divisionBracketGameParticipantTeamPool
ON divisionBracketGameParticipantTeamPool.Id = divisionBracketGameParticipant.Id
JOIN GrassrootsHoops.DivisionTeamPool divisionTeamPoolBracket
ON divisionTeamPoolBracket.Id = divisionBracketGameParticipantTeamPool.DivisionTeamPoolId
JOIN GrassrootsHoops.DivisionPool divisionTeamPoolPoolBracket
ON divisionTeamPoolPoolBracket.Id = divisionTeamPoolBracket.DivisionPoolId
JOIN GrassrootsHoops.DivisionTeam divisionTeamPoolTeamBracket
ON divisionTeamPoolTeamBracket.Id = divisionTeamPoolBracket.DivisionTeamId
JOIN GrassrootsHoops.Team teamPoolTeamBracket
ON teamPoolTeamBracket.Id = divisionTeamPoolTeamBracket.Id
WHERE
divisionGameTeamResult.HomeTeam = 1
AND
eventGame.[Type] = 1

Why query with MAX(Date) dosen't return any record?

I have a sql query like below:
SELECT CPH.CheckPointID,
CPH.ID AS Check_Point_History_ID,
CLCP.SequenceNo AS Sequence,
CP.Code AS Point_Code,
CPV.ID,
TT.Medium AS Description,
[TEXT_TRANSLATION_ANS].[Medium] AS Value,
CPH.Value_ AS Additional_Information,
EMP.NAME AS Checked_By,
CPH.AnsweredOn AS Checked_On
FROM CHECK_LIST_HISTORY CLH
LEFT JOIN CHECK_POINT_HISTORY CPH
ON CLH.ID = CPH.CheckListHistoryID
INNER JOIN (
SELECT CPH2.CheckPointID,
MAX(CPH2.AnsweredOn) AS MaxDate
FROM CHECK_LIST_HISTORY CLH2
LEFT JOIN CHECK_POINT_HISTORY CPH2
ON CLH2.ID = CPH2.CheckListHistoryID
GROUP BY CPH2.CheckPointID
) tm
ON CPH.CheckPointID = tm.CheckPointID
AND CPH.AnsweredOn = tm.MaxDate
LEFT JOIN CHECK_POINT CP
ON CPH.CheckPointID = CP.ID
LEFT JOIN CHECK_POINT_VALUE CPV
ON CPH.CheckPointValueID = CPV.ID
LEFT JOIN TEXT_TRANSLATION TT
ON CP.TextID = TT.TextID
AND TT.LanguageID = LanguageID
LEFT JOIN CHECK_LIST_CHECK_POINT CLCP
ON CP.ID = CLCP.CheckPointID
LEFT JOIN EMPLOYEE EMP
ON CPH.EmployeeID = EMP.ID
LEFT JOIN [TEXT_TRANSLATION] [TEXT_TRANSLATION_ANS]
ON CPV.AnswerTextID = [TEXT_TRANSLATION_ANS].[TextID]
AND [TEXT_TRANSLATION_ANS].[LanguageID] = TT.LanguageID
LEFT JOIN [TEXT_TRANSLATION] [TEXT_TRANSLATION_RES]
ON CPV.ResponseTextID = [TEXT_TRANSLATION_RES].[TextID]
AND [TEXT_TRANSLATION_RES].[LanguageID] = TT.LanguageID
WHERE CLH.WipOrderNo = 304
AND CLH.WipOrderType = 26
AND CLCP.WorkCenter = 'WC03'
AND CLCP.Facility = 'C1P1'
This query should return me two records with maximum date, but it returns nothing. I think the problem is in the INNER JOIN because when the line with the INNER JOIN is commented, the query returns the following table:

Error: Cannot use an aggregate or a subquery in an expression used for the group by list

I'm getting this error: Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause.
I searched on internet, but i don't know how to apply the correction in my case. I found different types of query only.
I'm trying to get a Count result in a field (line 5), but when I add the Count query i'm getting this error.
I'm using SQL SERVER 2008 R2.
When I remove the Count from SELECT and GROUP BY the query run correctly.
SELECT TF.COD_FORNECEDOR AS 'Cód. Fornec.',
TF.NOM_FANTASIA AS 'Fornecedor',
DM.COD_CONTRATO_RELACIONADO AS 'CONTRATO',
UA2.NOM_USUARIO AS 'NOM_USUARIO_COMPRADOR',
(SELECT COUNT(COD_CONTRATO_RELACIONADO) FROM TB_DEMANDA D INNER JOIN TB_PROCESSO P ON D.COD_CONTRATO_RELACIONADO = P.NUM_CONTRATO WHERE D.COD_CONTRATO_RELACIONADO = DM.COD_CONTRATO_RELACIONADO) AS 'NUM_ADITIVO',
0 AS 'Qtd. Aditivo',
SUM(DM.VAL_TOTAL_ORCADO) AS 'Valor Inicial',
SUM(TP.VAL_CONTRATADO) AS 'Valor Final',
((SUM(TP.VAL_CONTRATADO) / SUM(DM.VAL_TOTAL_ORCADO)) -1) * 100 AS 'Var. %'
FROM TB_FORNECEDOR TF
LEFT JOIN TB_DEMANDA DM ON DM.COD_FORNECEDOR = TF.COD_FORNECEDOR
LEFT JOIN TB_PROCESSO TP ON DM.COD_DEMANDA = TP.COD_DEMANDA
LEFT JOIN TB_PROCESSO_FORNECEDOR PF ON PF.COD_PROCESSO = TP.COD_PROCESSO
LEFT JOIN USUARIO UA ON UA.NUM_USUARIO = DM.NUM_USUARIO_COMPRADOR
LEFT JOIN USUARIO UA2 ON UA2.NUM_USUARIO = DM.NUM_USUARIO_COMPRADOR
LEFT JOIN TB_STATUS_DEMANDA_DATA SD ON SD.COD_DEMANDA = DM.COD_DEMANDA
LEFT JOIN TB_BASELINE BA ON BA.COD_PROCESSO = TP.COD_PROCESSO
LEFT JOIN TB_BASELINE_TAREFAS BT ON BT.COD_BASELINE = BA.COD_BASELINE AND BT.COD_PROCESSO = BA.COD_PROCESSO
LEFT JOIN TB_STATUS_PROCESSO SP ON SP.COD_STATUS = SD.COD_STATUS
LEFT JOIN TB_MEDIO_STATUS MS ON MS.COD_MEDIO_STATUS = SP.COD_MEDIO_STATUS
left JOIN #TB_PROCESSO TT ON TT.COD_PROCESSO = TP.COD_PROCESSO
GROUP BY
TF.COD_FORNECEDOR,
TF.NOM_FANTASIA,
DM.COD_CONTRATO_RELACIONADO,
UA2.NOM_USUARIO,
(SELECT COUNT(COD_CONTRATO_RELACIONADO) FROM TB_DEMANDA D INNER JOIN TB_PROCESSO P ON D.COD_CONTRATO_RELACIONADO = P.NUM_CONTRATO WHERE D.COD_CONTRATO_RELACIONADO = DM.COD_CONTRATO_RELACIONADO)
ORDER BY TF.NOM_FANTASIA
Try this:
SELECT TF.COD_FORNECEDOR AS 'Cód. Fornec.',
TF.NOM_FANTASIA AS 'Fornecedor',
DM.COD_CONTRATO_RELACIONADO AS 'CONTRATO',
UA2.NOM_USUARIO AS 'NOM_USUARIO_COMPRADOR',
sq.cnt AS 'NUM_ADITIVO',
0 AS 'Qtd. Aditivo',
SUM(DM.VAL_TOTAL_ORCADO) AS 'Valor Inicial',
SUM(TP.VAL_CONTRATADO) AS 'Valor Final',
((SUM(TP.VAL_CONTRATADO) / SUM(DM.VAL_TOTAL_ORCADO)) -1) * 100 AS 'Var. %'
FROM TB_FORNECEDOR TF
LEFT JOIN TB_DEMANDA DM ON DM.COD_FORNECEDOR = TF.COD_FORNECEDOR
LEFT JOIN TB_PROCESSO TP ON DM.COD_DEMANDA = TP.COD_DEMANDA
LEFT JOIN TB_PROCESSO_FORNECEDOR PF ON PF.COD_PROCESSO = TP.COD_PROCESSO
LEFT JOIN USUARIO UA ON UA.NUM_USUARIO = DM.NUM_USUARIO_COMPRADOR
LEFT JOIN USUARIO UA2 ON UA2.NUM_USUARIO = DM.NUM_USUARIO_COMPRADOR
LEFT JOIN TB_STATUS_DEMANDA_DATA SD ON SD.COD_DEMANDA = DM.COD_DEMANDA
LEFT JOIN TB_BASELINE BA ON BA.COD_PROCESSO = TP.COD_PROCESSO
LEFT JOIN TB_BASELINE_TAREFAS BT ON BT.COD_BASELINE = BA.COD_BASELINE AND BT.COD_PROCESSO = BA.COD_PROCESSO
LEFT JOIN TB_STATUS_PROCESSO SP ON SP.COD_STATUS = SD.COD_STATUS
LEFT JOIN TB_MEDIO_STATUS MS ON MS.COD_MEDIO_STATUS = SP.COD_MEDIO_STATUS
LEFT JOIN #TB_PROCESSO TT ON TT.COD_PROCESSO = TP.COD_PROCESSO
LEFT JOIN (
SELECT D.COD_CONTRATO_RELACIONADO, COUNT(COD_CONTRATO_RELACIONADO) AS cnt
FROM TB_DEMANDA D
INNER JOIN TB_PROCESSO P ON D.COD_CONTRATO_RELACIONADO = P.NUM_CONTRATO
GROUP BY D.COD_CONTRATO_RELACIONADO
) sq ON sq.COD_CONTRATO_RELACIONADO = DM.COD_CONTRATO_RELACIONADO
GROUP BY
TF.COD_FORNECEDOR,
TF.NOM_FANTASIA,
DM.COD_CONTRATO_RELACIONADO,
UA2.NOM_USUARIO,
sq.cnt
ORDER BY TF.NOM_FANTASIA
I integrated the num_aditivo subquery in a LEFT JOIN.