getting repeated rows - sql

I am not able to get why i am getting repeated data for below query. Although i have used distinct.
The query is as below- Please help :
Might be some problem with joins
SELECT DISTINCT(UM.USERNAME)'USER_NAME'
,UM.FIRSTNAME + ' ' + UM.LASTNAME AS 'EMPLOYEE NAME'
,US.USER_NAME 'USER_ID'
,US.MS_RIT_REPORTING_GROUP_MST_KEY
,RG.REPORTING_GROUP_NAME
,US.MS_RIT_REGION_MST_KEY
,RM.REGION_NAME
,US.MS_RIT_SUB_REGION_MST_KEY
,SM.SUB_REGION_NAME
,TP.TASK_MST_KEY
,TTM.TASK_TYPE_NAME
,CT.*
,FM.TASK_STATUS
,FM.TASK_START_DATE
,FM.TASK_END_DATE
,SRM.ROLE_NAME AS ROLENAME
FROM USERS_MASTER UM
INNER JOIN MS_RIT_USER_SKILLSET_MAP US ON UM.USERID = US.USER_NAME
INNER JOIN DIM_MS_RIT_REPORTING_GROUP_MST RG ON US.MS_RIT_REPORTING_GROUP_MST_KEY = RG.MS_RIT_REPORTING_GROUP_MST_KEY
AND UPPER(RG.ACTIVE) IN ('YES','1','Y')
INNER JOIN DIM_MS_RIT_REGION_MST RM ON US.MS_RIT_REGION_MST_KEY = RM.MS_RIT_REGION_MST_KEY
AND UPPER(RM.ACTIVE) IN ('YES','1','Y')
INNER JOIN DIM_MS_RIT_SUB_REGION_MST SM ON US.MS_RIT_SUB_REGION_MST_KEY = SM.MS_RIT_SUB_REGION_MST_KEY
AND UPPER(SM.ACTIVE) IN ('YES','1','Y')
INNER JOIN MS_RIT_USER_TASK_MAP TP ON CONVERT(VARCHAR,UM.USERID) = TP.USER_ID
INNER JOIN MS_RIT_CREATE_TASK CT ON CT.TASK_ID = TP.TASK_MST_KEY
INNER JOIN WF_FRM_28_MST FM ON FM.TASK_ID = CT.TASK_ID
INNER JOIN SEC_USER_ROLE SR ON SR.USER_ID = UM.USERNAME
INNER JOIN SEC_ROLE_MST SRM ON SRM.ROLE_CODE = SR.ROLE_CODE
INNER JOIN MS_RIT_TASK_TYPE_MASTER TTM ON CT.TASK_TYPE = TTM.TASK_TYPE_ID

Use UNION to get rid of duplicates
One solution to check if you have duplicates is to do a UNION using the same query, if no rows were removed then they are not duplicates.
(SELECT DISTINCT(UM.USERNAME)'USER_NAME'
,UM.FIRSTNAME + ' ' + UM.LASTNAME AS 'EMPLOYEE NAME'
,US.USER_NAME 'USER_ID'
,US.MS_RIT_REPORTING_GROUP_MST_KEY
,RG.REPORTING_GROUP_NAME
,US.MS_RIT_REGION_MST_KEY
,RM.REGION_NAME
,US.MS_RIT_SUB_REGION_MST_KEY
,SM.SUB_REGION_NAME
,TP.TASK_MST_KEY
,TTM.TASK_TYPE_NAME
,CT.*
,FM.TASK_STATUS
,FM.TASK_START_DATE
,FM.TASK_END_DATE
,SRM.ROLE_NAME AS ROLENAME
FROM USERS_MASTER UM
INNER JOIN MS_RIT_USER_SKILLSET_MAP US ON UM.USERID = US.USER_NAME
INNER JOIN DIM_MS_RIT_REPORTING_GROUP_MST RG ON US.MS_RIT_REPORTING_GROUP_MST_KEY = RG.MS_RIT_REPORTING_GROUP_MST_KEY
AND UPPER(RG.ACTIVE) IN ('YES','1','Y')
INNER JOIN DIM_MS_RIT_REGION_MST RM ON US.MS_RIT_REGION_MST_KEY = RM.MS_RIT_REGION_MST_KEY
AND UPPER(RM.ACTIVE) IN ('YES','1','Y')
INNER JOIN DIM_MS_RIT_SUB_REGION_MST SM ON US.MS_RIT_SUB_REGION_MST_KEY = SM.MS_RIT_SUB_REGION_MST_KEY
AND UPPER(SM.ACTIVE) IN ('YES','1','Y')
INNER JOIN MS_RIT_USER_TASK_MAP TP ON CONVERT(VARCHAR,UM.USERID) = TP.USER_ID
INNER JOIN MS_RIT_CREATE_TASK CT ON CT.TASK_ID = TP.TASK_MST_KEY
INNER JOIN WF_FRM_28_MST FM ON FM.TASK_ID = CT.TASK_ID
INNER JOIN SEC_USER_ROLE SR ON SR.USER_ID = UM.USERNAME
INNER JOIN SEC_ROLE_MST SRM ON SRM.ROLE_CODE = SR.ROLE_CODE
INNER JOIN MS_RIT_TASK_TYPE_MASTER TTM ON CT.TASK_TYPE = TTM.TASK_TYPE_ID)
UNION
(SELECT DISTINCT(UM.USERNAME)'USER_NAME'
,UM.FIRSTNAME + ' ' + UM.LASTNAME AS 'EMPLOYEE NAME'
,US.USER_NAME 'USER_ID'
,US.MS_RIT_REPORTING_GROUP_MST_KEY
,RG.REPORTING_GROUP_NAME
,US.MS_RIT_REGION_MST_KEY
,RM.REGION_NAME
,US.MS_RIT_SUB_REGION_MST_KEY
,SM.SUB_REGION_NAME
,TP.TASK_MST_KEY
,TTM.TASK_TYPE_NAME
,CT.*
,FM.TASK_STATUS
,FM.TASK_START_DATE
,FM.TASK_END_DATE
,SRM.ROLE_NAME AS ROLENAME
FROM USERS_MASTER UM
INNER JOIN MS_RIT_USER_SKILLSET_MAP US ON UM.USERID = US.USER_NAME
INNER JOIN DIM_MS_RIT_REPORTING_GROUP_MST RG ON US.MS_RIT_REPORTING_GROUP_MST_KEY = RG.MS_RIT_REPORTING_GROUP_MST_KEY
AND UPPER(RG.ACTIVE) IN ('YES','1','Y')
INNER JOIN DIM_MS_RIT_REGION_MST RM ON US.MS_RIT_REGION_MST_KEY = RM.MS_RIT_REGION_MST_KEY
AND UPPER(RM.ACTIVE) IN ('YES','1','Y')
INNER JOIN DIM_MS_RIT_SUB_REGION_MST SM ON US.MS_RIT_SUB_REGION_MST_KEY = SM.MS_RIT_SUB_REGION_MST_KEY
AND UPPER(SM.ACTIVE) IN ('YES','1','Y')
INNER JOIN MS_RIT_USER_TASK_MAP TP ON CONVERT(VARCHAR,UM.USERID) = TP.USER_ID
INNER JOIN MS_RIT_CREATE_TASK CT ON CT.TASK_ID = TP.TASK_MST_KEY
INNER JOIN WF_FRM_28_MST FM ON FM.TASK_ID = CT.TASK_ID
INNER JOIN SEC_USER_ROLE SR ON SR.USER_ID = UM.USERNAME
INNER JOIN SEC_ROLE_MST SRM ON SRM.ROLE_CODE = SR.ROLE_CODE
INNER JOIN MS_RIT_TASK_TYPE_MASTER TTM ON CT.TASK_TYPE = TTM.TASK_TYPE_ID)

Related

Long query mistake

I've just written a query here at work but I am getting "ORA-00920: invalid relational operator" when running it and I can't seem to find my mistake.
So here goes:
SELECT
D.DEPARTURE_NO,
D.DEPARTURE_DATE,
I.ITEM_GROUP_ID,
L.LUID,
OA.ADDRESS1,
OA.ADDRESS2,
OA.CITY,
OA.COUNTRY_CODE,
OA.NAME,
OA.POSTAL_CODE,
OA.RECEIVER_ID,
OC.COUNTRY_NAME,
OL.ORDER_LINE_NO,
O.INTERNAL_ORDER_ID,
O.RECEIVER_ORDER_ID,
O.STORER_ID,
O.STORER_ORDER_ID,
PL.BIN_LOCATION_ID,
PLL.PICK_STATUS,
PLL.PICKLIST_LINE_NO,
S.SHIPMENT_ID,
SH.NAME,
SH.SHIPPER_ID,
SS.SHIPPER_SERVICES_ID,
ST.NAME,
SA.ADDRESS_TYPE,
SA.ADDRESS1,
SA.ADDRESS2,
SA.ADDRESS3,
SA.CITY,
SA.POSTAL_CODE,
SC.COUNTRY_NAME,
VOPI.PARENT_INTERNAL_ORDER_ID
FROM
ORDERS O
INNER JOIN VY_ORDER_PARENT_ID VOPI ON VOPI.INTERNAL_ORDER_ID = O.INTERNAL_ORDER_ID
INNER JOIN VY_ORDER_PARENT_ID VOPI ON VOPI.INTERNAL_ORDER_ID = OA.INTERNAL_ORDER_ID
INNER JOIN ORDER_ADDRESS OA ON OA.INTERNAL_ORDER_ID = O.INTERNAL_ORDER_ID
INNER JOIN SHIPMENT S ON S.SHIPMENT_ID = O.SHIPMENT_ID
INNER JOIN SHIPPER_SERVICES SS ON SS.SHIPPER_SERVICES_NO = O.SHIPPER_SERVICES_NO
INNER JOIN STORER ST ON ST.STORER_ID = O.STORER_ID
INNER JOIN ORDER_LINE OL ON OL.INTERNAL_ORDER_ID = O.INTERNAL_ORDER_ID
INNER JOIN SHIPPER SH ON SH.SHIPPER_ID = O.SHIPPER_ID
INNER JOIN ORDER_COUNTRY OC ON OC.COUNTRY_CODE = OA.COUNTRY_CODE
INNER JOIN STORER_COUNTRY SC ON SC.COUNTRY_CODE OA.COUNTRY_CODE
INNER JOIN STORER_ADDRESS SA ON SA.COUNTRY_CODE = SC.STORER_ADDRESS
INNER JOIN STORER ST ON ST.STORER_ID = SA.STORER_ID
INNER JOIN DEPARTURE D ON D.ACTIVE_TRANSPORT_COUNTRY = SC.COUNTRY_CODE
INNER JOIN DEPARTURE D ON D.DEPARTURE_NO = S.DEPARTURE_NO
INNER JOIN ITEM I ON I.COUNTRY_CODE = SC.COUNTRY_CODE
INNER JOIN SHIPPER SH ON SH.SHIPPER_ID = S.SHIPPER_ID
INNER JOIN SHIPPER_SERVICES SS ON SS.SHIPPER_SERVICES_NO = S.SHIPPER_SERVICES_NO
INNER JOIN SHIPPER SH ON SH.SHIPPER_ID = SS.SHIPPER_ID
INNER JOIN IC_TRANSACTION ICT ON ICT.LUID_NO = L.LUID_NO
INNER JOIN PICKLIST_LINE PLL ON PLL.IC_TRANSACTION_NO = ICT.IC_TRANSACTION_NO
INNER JOIN LUID L ON L.STORER_ID = ST.STORER_ID
INNER JOIN ITEM I ON I.STORER_ID = ST.STORER_ID
INNER JOIN ITEM I ON I.ITEM_ID = OL.ITEM_ID AND I.STORER_ID = OL.ITEM_ID
INNER JOIN PICK_LOCATION PL ON PL.ITEM_ID = I.ITEM_ID AND PL.STORER_ID = I.ITEM_ID
INNER JOIN PICKLIST_LINE PLL ON PLL.EXPECTED_BIN_LOCATION_ID = PL.BIN_LOCATION_ID
INNER JOIN PICKLIST_LINE PLL ON PLL.EXPECTED_BUILDING_ID = PL.BUILDING_ID
INNER JOIN ORDER_LINE OL ON OL.INTERNAL_ORDER_ID = PLL.INTERNAL_ORDER_ID AND OL.ORDER_LINE_NO = PLL.ORDER_LINE_NO
WHERE S.SHIPMENT_ID = '2000518517'
Obviously you can't know the exact column names but I've gone through them multiple times and can't find any spelling errors.
Any other errors
INNER JOIN STORER_COUNTRY SC ON SC.COUNTRY_CODE OA.COUNTRY_CODE
should be
INNER JOIN STORER_COUNTRY SC ON SC.COUNTRY_CODE = OA.COUNTRY_CODE
and it looks like
INNER JOIN ORDER_LINE OL ON OL.INTERNAL_ORDER_ID = PLL.INTERNAL_ORDER_ID AND OL.ORDER_LINE NO = PLL.ORDER_LINE_NO
should be ( thanks to LONG )
INNER JOIN ORDER_LINE OL ON OL.INTERNAL_ORDER_ID = PLL.INTERNAL_ORDER_ID AND OL.ORDER_LINE_NO = PLL.ORDER_LINE_NO

SQL Nesting Logic Needed

I have a situation where I need to build a query that pulls gives me a list of member that used an item on their account in timeframe one but that did not use on item on their account in timeframe two.
SELECT DISTINCT SS.memid
FROM SS
INNER JOIN SSUSED ON SS.ssid = SSUSED.ssid
INNER JOIN MEMBERS AS MEMBERS_1 ON SS.memid = MEMBERS_1.memid
INNER JOIN PRODUCTS ON SS.productid = PRODUCTS.productid
INNER JOIN PRODUCTCATS ON PRODUCTS.productcatid = PRODUCTCATS.productcatid
INNER JOIN EMPLOYEES ON SSUSED.employeeid = EMPLOYEES.employeeid
AND NOT EXISTS
(
SELECT DISTINCT SS_1.memid
FROM SS AS SS_1
INNER JOIN SSUSED AS SSUSED_1 ON SS_1.ssid = SSUSED_1.ssid
INNER JOIN MEMBERS AS MEMBERS_1 ON SS_1.memid = MEMBERS_1.memid
INNER JOIN PRODUCTS AS PRODUCTS_1 ON SS_1.productid = PRODUCTS_1.productid
INNER JOIN PRODUCTCATS AS PRODUCTCATS_1 ON PRODUCTS_1.productcatid = PRODUCTCATS_1.productcatid
INNER JOIN EMPLOYEES AS EMPLOYEES_1 ON SSUSED_1.employeeid = EMPLOYEES_1.employeeid
WHERE
MEMBERS_1.siteid = #rvSite
AND SSUSED_1.usedate BETWEEN #rvStartWeek2
AND #rvEndWeek2
AND PRODUCTS_1.productcatid IN (27,28,29,58,77,75,30,61,31,32,47,68)
)
WHERE MEMBERS_1.siteid = #rvSite
AND SSUSED.usedate BETWEEN #rvStartWeek1
AND #rvEndWeek1
AND PRODUCTS.productcatid IN (27,28,29,58,77,75,30,61,31,32,47,68)
The issue that I am running into is that when I try the query this way I get the following error:

Take MAX TransactionId from LEFT JOIN SQL

Hi i have one sql query in sql server that looks like
SELECT
DTST.[Id],
FPT.[StartTime],
--FPT.[BusinessTypeId],
FPT.[PaymentMethodId],
FPT.[3DSecureId],
FPT.[ProductId],
DPT.[Id],
FPT.[TransactionStatusId],
FPT.[Amount],
DC.[Code],
FPT.[PlayerId],
DPL.[SourceOrigId],
DPL.[Username],
DPL.[FirstName],
DPL.[LastName],
DPL.[BrandId],
DPL.[VIPLevelId],
DPL.[MarketingChannelId],
DPL.[MarketingSourceId],
FPT.[PaymentReasonTextId],
FPT_Ref.[PaymentReasonTextId],
AD.Username,
FPT.[OriginalTransactionId],
FPT.[TransactionId],
FPT_Ref.[OriginalTransactionId],
FPT.[ProviderTransactionOrigId]
FROM WarehouseMgmt.FactPaymentTrans AS FPT
JOIN
(
SELECT TransactionId,MAX(TransactionStepId) TransactionStepId
FROM [WarehouseMgmt].[FactPaymentTrans]
WHERE FactType = ''SOURCE''
GROUP BY TransactionId
) AS FPT_Last ON FPT.TransactionId = FPT_Last.TransactionId AND FPT.TransactionStepId = FPT_Last.TransactionStepId
JOIN WarehouseMgmt.DimTransactionStepType AS DTST ON FPT.[TransactionStepTypeId] = DTST.[Id]
JOIN WarehouseMgmt.DimCurrency AS DC ON FPT.CurrencyId = DC.Id
JOIN WarehouseMgmt.DimPlayer AS DPL ON FPT.PlayerId = DPL.Id
JOIN WarehouseMgmt.DimProduct AS DP ON DP.Id = FPT.ProductId
JOIN WarehouseMgmt.DimProductType AS DPT ON DPT.Id = DP.ProductTypeId
JOIN [WarehouseMgmt].[DimLoyaltyProgramLevel] DLPL ON DLPL.[Id]=DPL.VipLevelId
JOIN WarehouseMgmt.DimAdmin AS AD ON AD.Id=FPT.CreatedByAdminId
JOIN WarehouseMgmt.DimPaymentTransactionBusinessType AS DPTBT ON DPTBT.Id = FPT.BusinessTypeId
JOIN WarehouseMgmt.DimTransactionStatus TS ON TS.Id= FPT.TransactionStatusId
JOIN WarehouseMgmt.DimPaymentMethod DPM ON DPM.Id = FPT.[PaymentMethodId]
JOIN WarehouseMgmt.DimTimeZone DTZ on FPT.[TimeId] = DTZ.TimeUTCId
LEFT JOIN [WarehouseMgmt].[FactPaymentTrans] FPT_Ref ON FPT_Ref.OriginalTransactionId = FPT.TransactionId AND FPT_Ref.FactType = ''SOURCE''
WHERE (FPT.FactType = ''SOURCE'')
AND DTZ.TimeId BETWEEN #DimStartDate AND #DimEndDate ' + #sqlFilters
With this query i have duplicated transactions, because of LEFT JOIN. How can i improve my LEFT JOIN to take only MAX TransactionId in from LEFT JOIN ?

MSSQL How do I get average of four records from different tables?

I have four tables and I need to find the average of each score for a particular id. I do not need the ENTIRE Column average, but the average of each record with the same id in each table.
I have tried this:
SELECT DISTINCT M.system_id, S.name, SUM(A.Score + WAL.score + F.score + WIN.score) / 4
AS avgScore
FROM dbo.T3_MovementSystemJoin AS M
INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id
INNER JOIN T3_ApplicationSystemJoin AS A ON A.Application_id = #application_id
INNER JOIN T3_WallTypeSystemJoin AS WAL ON WAL.wall_id = #wall_id
INNER JOIN T3_FenestrationSystemJoin AS F ON F.fenestration_id = #fen_id
INNER JOIN T3_WindowOrientation_System AS WIN ON WIN.window_id = #window_id
INNER JOIN T3_ConstructionSystemJoin AS C ON C.contruction_id = #construction_id
INNER JOIN T3_JointDepthSystemJoin AS J ON J.JointDepth_id = #JointDepth_id
INNER JOIN T3_JointGapSystemJoin AS JG ON JG.JointGap_id = #JointGap_id
WHERE (M.movement_id = #movement_id)
GROUP BY M.System_id, S.name
:
Thanks for your help!
No Sum needed (and no grouping too)
SELECT DISTINCT M.system_id, S.name, (IsNull(A.Score, 0) + IsNull(WAL.score, 0) + IsNull(F.score, 0) + IsNull(WIN.score, 0)) /4
as avgscore
FROM dbo.T3_MovementSystemJoin AS M
INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id
INNER JOIN T3_ApplicationSystemJoin AS A ON A.Application_id = #application_id
INNER JOIN T3_WallTypeSystemJoin AS WAL ON WAL.wall_id = #wall_id
INNER JOIN T3_FenestrationSystemJoin AS F ON F.fenestration_id = #fen_id
INNER JOIN T3_WindowOrientation_System AS WIN ON WIN.window_id = #window_id
INNER JOIN T3_ConstructionSystemJoin AS C ON C.contruction_id = #construction_id
INNER JOIN T3_JointDepthSystemJoin AS J ON J.JointDepth_id = #JointDepth_id
INNER JOIN T3_JointGapSystemJoin AS JG ON JG.JointGap_id = #JointGap_id
WHERE (M.movement_id = #movement_id)
SELECT DISTINCT M.system_id
,S.name
,(ISNULL(A.Score,0) + ISNULL(WAL.score,0) + ISNULL(F.score,0) + ISNULL(WIN.score,0)) /4 as 'AvgScore'
FROM dbo.T3_MovementSystemJoin AS M
INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id
INNER JOIN T3_ApplicationSystemJoin AS A ON A.Application_id = #application_id
INNER JOIN T3_WallTypeSystemJoin AS WAL ON WAL.wall_id = #wall_id
INNER JOIN T3_FenestrationSystemJoin AS F ON F.fenestration_id = #fen_id
INNER JOIN T3_WindowOrientation_System AS WIN ON WIN.window_id = #window_id
INNER JOIN T3_ConstructionSystemJoin AS C ON C.contruction_id = #construction_id
INNER JOIN T3_JointDepthSystemJoin AS J ON J.JointDepth_id = #JointDepth_id
INNER JOIN T3_JointGapSystemJoin AS JG ON JG.JointGap_id = #JointGap_id
WHERE (M.movement_id = #movement_id)
If you don't want NULL values to become zeros and included in the average:
SELECT DISTINCT M.system_id, S.name, X.avgScore
FROM dbo.T3_MovementSystemJoin AS M
INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id
INNER JOIN T3_ApplicationSystemJoin AS A ON A.Application_id = #application_id
INNER JOIN T3_WallTypeSystemJoin AS WAL ON WAL.wall_id = #wall_id
INNER JOIN T3_FenestrationSystemJoin AS F ON F.fenestration_id = #fen_id
INNER JOIN T3_WindowOrientation_System AS WIN ON WIN.window_id = #window_id
INNER JOIN T3_ConstructionSystemJoin AS C ON C.contruction_id = #construction_id
INNER JOIN T3_JointDepthSystemJoin AS J ON J.JointDepth_id = #JointDepth_id
INNER JOIN T3_JointGapSystemJoin AS JG ON JG.JointGap_id = #JointGap_id
CROSS APPLY ( SELECT AVG(s) FROM (VALUES (A.Score),(WAL.score),(F.score),(WIN.score) ) scores(s) ) X(avgScore)
WHERE (M.movement_id = #movement_id)
GROUP BY M.System_id, S.name

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.