I use a system that doesn't allow me access to the SQL database directly and I have to use their in built reporting tool which is just awful. I'm running the below code and its telling me there is a syntax error near ) but I can't see myself how this is incorrect, any ideas?
SELECT ST.Staff_ID,
COUNT (CASE WHEN Referral_Date BETWEEN #StartDate AND #EndDate ) AS 'Referrals',
COUNT (CASE WHEN Att_Start_Dttm BETWEEN #StartDate AND #EndDate ) AS 'Appointments'
FROM tbldiaryappointment DA
left outer join tblDiaryAppointmentClinicianInvitee CI on DA.Diary_Appointment_ID = CI.Diary_Appointment_ID
left outer join tblstaff ST on CI.Clinician_Invitee_Staff_ID = ST.STaff_ID
left outer join tbllocation LOC on LOC.Location_ID = DA.Scheduled_Location_ID
left outer join tblpatient PAT on PAT.Patient_ID = DA.Patient_ID
left outer join tblAttendanceTypeValues ATV on ATV.Attendance_Type_ID = DA.Attendance_Type_ID
left outer join tblDiaryAppointmentScheduledEvent SE on SE.Diary_Appointment_ID = DA.Diary_Appointment_ID
left outer join tblEventValues EVE on EVE.Event_ID = SE.Event_ID
left outer join tblProfessionalGroupValues PGV on ST.Professional_Group_ID = PGV.Professional_Group_ID
left outer join tblStaffJobRoleCodeValues JOB on JOB.Staff_Job_Role_Code_ID = ST.Job_Role_Code_ID
left outer join tblReferral REF on REF.Patient_ID = DA.Patient_ID
Syntax for Searched CASE expression is:
CASE
WHEN Boolean_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
You're missing the part after Boolean_expression.
Also, your statement is missing GROUP BY clause.
SELECT ST.Staff_ID,
COUNT (CASE WHEN Referral_Date BETWEEN #StartDate AND #EndDate THEN 1 END) AS 'Referrals',
COUNT (CASE WHEN Att_Start_Dttm BETWEEN #StartDate AND #EndDate THEN 1 END ) AS 'Appointments'
FROM tbldiaryappointment DA
left outer join tblDiaryAppointmentClinicianInvitee CI on DA.Diary_Appointment_ID = CI.Diary_Appointment_ID
left outer join tblstaff ST on CI.Clinician_Invitee_Staff_ID = ST.STaff_ID
left outer join tbllocation LOC on LOC.Location_ID = DA.Scheduled_Location_ID
left outer join tblpatient PAT on PAT.Patient_ID = DA.Patient_ID
left outer join tblAttendanceTypeValues ATV on ATV.Attendance_Type_ID = DA.Attendance_Type_ID
left outer join tblDiaryAppointmentScheduledEvent SE on SE.Diary_Appointment_ID = DA.Diary_Appointment_ID
left outer join tblEventValues EVE on EVE.Event_ID = SE.Event_ID
left outer join tblProfessionalGroupValues PGV on ST.Professional_Group_ID = PGV.Professional_Group_ID
left outer join tblStaffJobRoleCodeValues JOB on JOB.Staff_Job_Role_Code_ID = ST.Job_Role_Code_ID
left outer join tblReferral REF on REF.Patient_ID = DA.Patient_ID
GROUP BY ST.Staff_ID
Related
I have the below query, and for some reason the Left Outer Join to PO_HEADERS_ALL POH is causing the error ORA-00918: column ambiguously defined on Left Outer Join. I don't have any columns selected from this table that would be causing this error from what I see. If I comment out this join then the query validates successfully. Appreciate any assistance on this, thanks!
SELECT
ESIB.ITEM_NUMBER,
ESIT.LONG_DESCRIPTION,
IOP.ORGANIZATION_CODE,
IOQD.SUBINVENTORY_CODE,
SUM(
IOQD.PRIMARY_TRANSACTION_QUANTITY
) ONHAND_QTY,
ESIB.PRIMARY_UOM_CODE ONHAND_UOM,
UOM.UOM_CODE TO_UOM,
INTRACONV.CONVERSION_RATE
, SEGMENT1||'-'||SEGMENT2||'-'||SEGMENT3||'-'||SEGMENT4||'-'||SEGMENT5 LOCATOR
,hp.party_name MFG
,etp.tp_item_number MFG_PART_NUM
FROM
EGP_SYSTEM_ITEMS_B ESIB
LEFT OUTER JOIN EGP_SYSTEM_ITEMS_TL ESIT ON ESIB.INVENTORY_ITEM_ID = ESIT.INVENTORY_ITEM_ID
AND ESIB.ORGANIZATION_ID = ESIT.ORGANIZATION_ID --Ended
INNER JOIN INV_ONHAND_QUANTITIES_DETAIL IOQD ON ESIB.INVENTORY_ITEM_ID = IOQD.INVENTORY_ITEM_ID
AND ESIB.ORGANIZATION_ID = IOQD.ORGANIZATION_ID
LEFT OUTER JOIN inv_item_locations LOC ON inventory_location_id= IOQD.locator_id
LEFT OUTER JOIN egp_item_relationships_b eir ON eir.inventory_item_id = ESIB.inventory_item_id and eir.item_relationship_type = 'MFG_PART_NUM'
LEFT OUTER JOIN egp_trading_partner_items etp ON etp.tp_item_id = eir.tp_item_id
and etp.tp_type = 'MANUFACTURER'
LEFT OUTER JOIN hz_parties hp ON hp.party_id = etp.trading_partner_id
LEFT OUTER JOIN PO_LINES_ALL POL ON POL.ITEM_ID = ESIB.INVENTORY_ITEM_ID
--ERROR IS OCCURING WITH THE FOLLOWING JOIN:
LEFT OUTER JOIN PO_HEADERS_ALL POH ON POH.PO_HEADER_ID = POL.PO_HEADER_ID
INNER JOIN INV_UNITS_OF_MEASURE_B UOM ON UOM.BASE_UOM_FLAG = 'Y'
LEFT OUTER JOIN INV_UOM_CONVERSIONS INTRACONV ON --INTRACONV.UOM_CODE = IOQD.TRANSACTION_UOM_CODE
INTRACONV.UOM_CODE = ESIB.PRIMARY_UOM_CODE
AND UOM.UOM_CLASS = INTRACONV.UOM_CLASS
AND INTRACONV.INVENTORY_ITEM_ID = IOQD.INVENTORY_ITEM_ID
--AND INTRACONV.UOM_CODE = UOM.UOM_CODE
INNER JOIN INV_ORG_PARAMETERS IOP ON ESIB.ORGANIZATION_ID = IOP.ORGANIZATION_ID
WHERE
(
INTRACONV.UOM_CODE = IOQD.TRANSACTION_UOM_CODE
OR ESIB.PRIMARY_UOM_CODE = UOM.UOM_CODE
)
GROUP BY
ESIB.ITEM_NUMBER,
ESIT.LONG_DESCRIPTION,
IOP.ORGANIZATION_CODE,
IOQD.SUBINVENTORY_CODE,
ESIB.PRIMARY_UOM_CODE,
UOM.UOM_CODE,
INTRACONV.CONVERSION_RATE
, SEGMENT1||'-'||SEGMENT2||'-'||SEGMENT3||'-'||SEGMENT4||'-'||SEGMENT5
,hp.party_name
,etp.tp_item_number
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).
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
I probably messed that title up! So I have a column called "programID" and I want another column to tell me the most recent date an order was placed using the programID. I think I'd need a subcolumn but the problem is how do I use the row's programID so that it matches the programID for the same row?
DECLARE #ClientIDs varchar(4) = 6653;
DECLARE #ProgramStatus char(1) = 'Y'; -- Y, N, or R
SELECT
rcp.RCPID AS ProgramID
, rcp.RCPName AS Program
, rcp.RCPActive AS ProgramStatus
, aa.AACustomCardInternalReview AS VCCP
, aa.AAJobNo AS AAJobNo
, aas.AASName AS AAStatus
, rcp.RCPOpsApproved AS OpsApproved
, clt.CltID AS ClientID
, rcp.RCPSignatureRequired AS SignatureRequired
, st.STEnumValue AS DefaultShipType
, rcp.RCPShipMethodOverrideType AS ShipTypeOverride
,aa.AANetworkProgramID
,(Select max(cdconfirmationdate) from carddet where ) --can't figure this part out
FROM
RetailerCardProgram rcp WITH (NOLOCK)
INNER JOIN ClientRetailerMap crm WITH (NOLOCK)
ON crm.CRMRetailerID = rcp.RCPRetailerID
INNER JOIN Client clt WITH(NOLOCK)
ON clt.CltID = crm.CRMCltID
LEFT JOIN AssociationApproval aa WITH (NOLOCK)
ON aa.AARetailerID = rcp.RCPRetailerID
AND aa.AABin = rcp.RCPBin6
AND aa.AAFrontOfPlasticTemplateID = rcp.RCPFOCTemplateID
AND aa.AABackOfPlasticTemplateID = rcp.RCPBOCTemplateID
AND ISNULL(aa.AACardID, 0) = ISNULL(rcp.RCPDefaultPlasticCardID, 0)
-- AND LOWER(rcp.RCPName) NOT LIKE '%do not use%' -- Needed for AA Job Number 1594
LEFT JOIN AssociationApprovalStatus aas WITH (NOLOCK)
ON aas.AASID = aa.AAAssociationApprovalStatusID
LEFT JOIN OpenLoopAssociation ola WITH (NOLOCK)
ON ola.OLAID=rcp.RCPOLAID
LEFT JOIN ClientCardProgramMap ccpm WITH (NOLOCK)
ON ccpm.CCPMCardProgramID = rcp.RCPID
AND ccpm.CCPMClientID = clt.CltID
LEFT JOIN TippingModule tm WITH (NOLOCK)
ON tm.TMid = rcp.RCPTippingModuleID
LEFT JOIN GiftCardTemplate fgt WITH (NOLOCK)
ON fgt.gtid = rcp.RCPFOCTemplateID
AND fgt.GTPage='P'
LEFT JOIN GiftCardTemplate bgt WITH (NOLOCK)
ON bgt.gtid = rcp.RCPBOCTemplateID
AND bgt.GTPage='PB'
LEFT JOIN Card c WITH (NOLOCK)
ON c.CardID = rcp.RCPDefaultCarrierID
LEFT JOIN CardType ct WITH (NOLOCK)
ON ct.CTID = c.CardTypeID
LEFT JOIN RetailerCardProgramTCSheetMap rtm1 WITH (NOLOCK)
ON rtm1.RTMRCPID = rcp.RCPID
AND rtm1.RTMInsertOrder = 1
LEFT JOIN RetailerCardProgramTCSheetMap rtm2 WITH (NOLOCK)
ON rtm2.RTMRCPID = rcp.RCPID
AND rtm2.RTMInsertOrder = 2
LEFT JOIN RetailerCardProgramTCSheetMap rtm3 WITH (NOLOCK)
ON rtm3.RTMRCPID = rcp.RCPID
AND rtm3.RTMInsertOrder = 3
LEFT JOIN RetailerCardProgramTCSheetMap rtm4 WITH (NOLOCK)
ON rtm4.RTMRCPID = rcp.RCPID
AND rtm4.RTMInsertOrder = 4
LEFT JOIN TCSheet i1 WITH (NOLOCK)
ON i1.TCSID = rtm1.RTMTCSID
LEFT JOIN TCSheet i2 WITH (NOLOCK)
ON i2.TCSID = rtm2.RTMTCSID
LEFT JOIN TCSheet i3 WITH (NOLOCK)
ON i3.TCSID = rtm3.RTMTCSID
LEFT JOIN TCSheet i4 WITH (NOLOCK)
ON i4.TCSID = rtm4.RTMTCSID
LEFT JOIN ShipType st WITH (NOLOCK)
ON st.STId = rcp.RCPDefaultShipTypeID
WHERE
clt.CltID IN (#ClientIDs) -- 6653 and 6657.
AND rcp.RCPActive IN (#ProgramStatus)
ORDER BY
AAJobNo
, Program
You want to join with a nested select on the table carddet. I'm inferring that RCPID is the relationship between carddet and your main table RetainerCardProgram...
SELECT rcp.RCPID AS ProgramID,
date.MAXDATE AS MaxDate,
rest of your columns...
FROM RetailerCardProgram rcp WITH (NOLOCK)
INNER JOIN (
SELECT RCPID, MAX(cdconfirmationdate) as 'MAXDATE'
FROM carddet
GROUP BY RCPID
) date on date.RCPID = rcp.RCPID
rest of query...
You may want a left join if not all IDs have a date in carddet.
Obligatory addition: Also your use of NOLOCK is a bit terrifying. See http://blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere/
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.