Optimizing Multiple SQL Queries - sql

I have 2 queries that I want to optimize but I don't know how. The execution time is not acceptable for me.
I'm working with jira database and did query to show different tasks with some attributes.
The code is:
SET NOCOUNT ON
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2
SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
,concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка'
,p.[pname] AS 'П'
,users.[display_name] AS 'Исполнитель'
,CAST(ji.[CREATED] AS smalldatetime) AS 'Создан'
,CAST(ji.[RESOLUTIONDATE] AS smalldatetime) AS 'Дата резолюции'
,ji.[issuenum]
INTO #TT
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [priority] AS p ON (p.[ID] = ji.[PRIORITY])
LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [cwd_user] as users ON (users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND itype.pname = 'Incident'
SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
,system_t.[NAME] AS 'Контур ИС'
,system_t_t.[NAME] AS 'Критичность системы'
INTO #TT1
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t ON (system_t.[ID] = substring(customfv.[STRINGVALUE], PatIndex('%[0-9]%', customfv.[STRINGVALUE]), len(customfv.[STRINGVALUE])))
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR] AS system_attr ON (system_t.[ID] = system_attr.[OBJECT_ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR_VAL] AS system_attr_val ON (system_attr.[ID] = system_attr_val.[OBJECT_ATTRIBUTE_ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t_t ON (system_attr_val.[REFERENCED_OBJECT_ID] = system_t_t.[ID])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND (customfv.[CUSTOMFIELD] = 21003 OR customfv.[CUSTOMFIELD] = 21005)
AND (system_t.[OBJECT_TYPE_ID] = 136 OR system_t.[OBJECT_TYPE_ID] = 303 OR system_t.[OBJECT_TYPE_ID] = 143)
AND system_attr.[OBJECT_TYPE_ATTRIBUTE_ID] = 461
AND itype.pname = 'Incident'
SELECT ji.[issuenum]
,pr_pr.[pname] AS '(project) Project'
INTO #TT2
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
LEFT OUTER JOIN [project] AS pr_pr ON (pr_pr.[ID] = CAST(customfv.[NUMBERVALUE] AS BIGINT))
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND pr_pr.[pname] is not NULL
SELECT CTE.[Ключ], CTE.[Ссылка], CTE.[П], CTE.[Исполнитель], CTE.[Создан], CTE.[Дата резолюции], CTE2.[(project) Project], CTE1.[Контур ИС], CTE1.[Критичность системы], CTE.[issuenum]
FROM #TT CTE
LEFT OUTER JOIN #TT1 CTE1 ON (CTE1.[Ключ] = CTE.[Ключ])
LEFT OUTER JOIN #TT2 CTE2 ON (CTE2.[issuenum] = CTE.[issuenum])
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2
There will be some information for the month before last.
summary of query
The next query is:
WITH CTE AS (
SELECT concat(p.pkey,'-',i.issuenum) AS 'Ключ',
cf.cfname,
cv.textvalue,
ROW_NUMBER() OVER (PARTITION BY i.issuenum ORDER BY i.issuenum) AS RowNumber_SLA
FROM customfield cf,
customfieldvalue cv,
jiraissue i,
project p
WHERE i.project = p.id
AND cv.issue = i.id
AND cv.customfield = cf.id
AND cf.customfieldtypekey = 'com.atlassian.servicedesk:sd-sla-field'
and i.issuenum IN ()
and CHARINDEX('"succeeded":false', TEXTVALUE) >0
)
SELECT CTE.Ключ
FROM CTE
WHERE RowNumber_SLA = 1
The goal is to get tasks where SLA has been failed.
So in and i.issuenum IN () my Python script is putting issue numbers that I got through previous query.
The average execution time is 3 minutes.
So, I want optimize this too, maybe join first query.
Sorry for my English. I'm not an English-speaking person.
P. S. Changing CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done' to ci.[NEWSTRING] = 'Done' causing the error The data types ntext and varchar are incompatible in the equal to operator. Workaround - ci.[NEWSTRING] LIKE 'Done' fixing this.

The first query must be rewrite as :
SELECT DISTINCT
concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ',
concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка',
p.[pname] AS 'П',
users.[display_name] AS 'Исполнитель',
CAST(ji.[CREATED] AS SMALLDATETIME) AS 'Создан',
CAST(ji.[RESOLUTIONDATE] AS SMALLDATETIME) AS 'Дата резолюции',
ji.[issuenum]
INTO #TT
FROM [jiraissue] AS ji
INNER JOIN [changegroup] AS cg ON(cg.[issueid] = ji.[id])
INNER JOIN [changeitem] AS ci ON(ci.[groupid] = cg.[id])
AND ci.FIELDTYPE = 'jira'
AND ci.FIELD = 'status'
LEFT OUTER JOIN [app_user] AS au ON(au.[user_key] = cg.[AUTHOR])
INNER JOIN [issuetype] AS itype ON(itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [priority] AS p ON(p.[ID] = ji.[PRIORITY])
LEFT OUTER JOIN [project] AS pr ON(pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [cwd_user] AS users ON(users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(DATETIME, '2021-12-01')
AND cg.[CREATED] <= CONVERT(DATETIME, '2022-01-01')
AND ci.[NEWSTRING] = 'Done'
AND itype.pname = 'Incident';
False outer joins are converted in INNER and I have aslo eliminate the ugly CONVERT to NVARCHAR(max)
Same troubles appears in the second query...

Related

using CTE while declaring variables in SQL

I have two decraed variables and I am trying to set the values from the result of my CTE,
declare #Total_new_claims_received int
declare #Total_Claims_Processed int
End solution I'm looking for is being able to set both declared values from CTE results:
select #Total_new_claims_received = count(id)
from cte
where benefit_code_id not in ('739')
select #Total_Claims_Processed = count(id)
from cte2
where benefit_code_id not in ('739')
Current Code:
declare #Total_new_claims_received int
declare #Total_Claims_Processed int
with cte (ID, Date)
as (
select c.id, c.date
from axiscore.dbo.claim c with (nolock)
inner join claim_line cl on c.Claim_ID = cl.Claim_ID and cl.Linenum = 1
left join axiscore.dbo.member_policy mp with (nolock) on c.Member_Policy_ID = mp.Member_Policy_ID
left join axiscore.dbo.policy p with (nolock) on mp.policy_id = p.policy_id
inner join axiscore.dbo.Claim_Status s with (nolock) on c.Claim_Status_ID = s.Claim_Status_ID
left outer join axiscore.dbo.Claim_Reason_Type r with (nolock) on c.Claim_Reason_Type_ID = r.Claim_Reason_Type_ID
where
c.Updated_Date between '10-1-2019' and '10-31-2019'
and p.Payor_ID = 8
and (c.Claim_Status_ID <> 8)),
cte2 (ID, Date)
as
(
select c.id, c.date
from axiscore.dbo.claim c with (nolock)
inner join claim_line cl on c.Claim_ID = cl.Claim_ID and cl.Linenum = 1
left join axiscore.dbo.member_policy mp with (nolock) on c.Member_Policy_ID = mp.Member_Policy_ID
left join axiscore.dbo.policy p with (nolock) on mp.policy_id = p.policy_id
inner join axiscore.dbo.Claim_Status s with (nolock) on c.Claim_Status_ID = s.Claim_Status_ID
left outer join axiscore.dbo.Claim_Reason_Type r with (nolock) on c.Claim_Reason_Type_ID = r.Claim_Reason_Type_ID
where
c.Updated_Date between '10-1-2019' and '10-31-2019'
and p.Payor_ID = 8
and (c.Claim_Status_ID in (7,6))
and (c.Claim_Reason_Type_ID not in (136,137)))
select #Total_new_claims_received = count(id)
from cte
where benefit_code_id not in ('739')
select #Total_Claims_Processed = count(id)
from cte2
where benefit_code_id not in ('739')
Currently,
it's only setting the value for Total_new_claims_received. It errors out on the second select when I'm setting the value for Total_Claims_Processed. The error is 'invalid object name 'cte2'.
I'm using CTE instead of temp tables becuase I'm calling this proc in a SSIS package. SSIS package doesn't do well with Temp tables. Any other ideas welcome as well.
thanks for your time!
From WITH common_table_expression (Transact-SQL):
A CTE must be followed by a single SELECT, INSERT, UPDATE, or
DELETE statement that references some or all the CTE columns
So define each of your CTEs before each of the select statements that uses it:
declare #Total_new_claims_received int
declare #Total_Claims_Processed int
with cte (ID, Date) as (
select c.id, c.date
from axiscore.dbo.claim c with (nolock)
inner join claim_line cl on c.Claim_ID = cl.Claim_ID and cl.Linenum = 1
left join axiscore.dbo.member_policy mp with (nolock) on c.Member_Policy_ID = mp.Member_Policy_ID
left join axiscore.dbo.policy p with (nolock) on mp.policy_id = p.policy_id
inner join axiscore.dbo.Claim_Status s with (nolock) on c.Claim_Status_ID = s.Claim_Status_ID
left outer join axiscore.dbo.Claim_Reason_Type r with (nolock) on c.Claim_Reason_Type_ID = r.Claim_Reason_Type_ID
where
c.Updated_Date between '10-1-2019' and '10-31-2019'
and p.Payor_ID = 8
and (c.Claim_Status_ID <> 8)
)
select #Total_new_claims_received = count(id)
from cte
where benefit_code_id not in ('739');
with cte2 (ID, Date) as (
select c.id, c.date
from axiscore.dbo.claim c with (nolock)
inner join claim_line cl on c.Claim_ID = cl.Claim_ID and cl.Linenum = 1
left join axiscore.dbo.member_policy mp with (nolock) on c.Member_Policy_ID = mp.Member_Policy_ID
left join axiscore.dbo.policy p with (nolock) on mp.policy_id = p.policy_id
inner join axiscore.dbo.Claim_Status s with (nolock) on c.Claim_Status_ID = s.Claim_Status_ID
left outer join axiscore.dbo.Claim_Reason_Type r with (nolock) on c.Claim_Reason_Type_ID = r.Claim_Reason_Type_ID
where
c.Updated_Date between '10-1-2019' and '10-31-2019'
and p.Payor_ID = 8
and (c.Claim_Status_ID in (7,6))
and (c.Claim_Reason_Type_ID not in (136,137))
)
select #Total_Claims_Processed = count(id)
from cte2
where benefit_code_id not in ('739');

why selecting particular columns from same table slows down query performance significantly?

I have SELECT statement that querying columns from tblQuotes. Why if I am selecting columns a.ProducerCompositeCommission and a.CompanyCompositeCommission, then query spinning forever.
Execution plans with and without those columns are IDENTICAL!
If I commented them out - then it brings result for 1 second.
SELECT
a.stateid risk_state1,
--those columns slows down performance
a.ProducerCompositeCommission,
a.CompanyCompositeCommission,
GETDATE() runDate
FROM
tblQuotes a
INNER JOIN
lstlines l ON a.LineGUID = l.LineGUID
INNER JOIN
tblSubmissionGroup tsg ON tsg.SubmissionGroupGUID = a.SubmissionGroupGuid
INNER JOIN
tblUsers u ON u.UserGuid = tsg.UnderwriterUserGuid
INNER JOIN
tblUsers u2 ON u2.UserGuid = a.UnderwriterUserGuid
LEFT OUTER JOIN
tblFin_Invoices tfi ON tfi.QuoteID = a.QuoteID AND tfi.failed <> 1
INNER JOIN
lstPolicyTypes lpt ON lpt.policytypeid = a.policytypeid
INNER JOIN
tblproducercontacts prodC ON prodC.producercontactguid = a.producercontactguid
INNER JOIN
tblProducerLocations pl ON pl.producerlocationguid = prodc.producerlocationguid
INNER JOIN
tblproducers prod ON prod.ProducerGUID = pl.ProducerGUID
LEFT OUTER JOIN
Catalytic_tbl_Model_Analysis aia ON aia.ImsControl = a.controlno
AND aia.analysisid = (SELECT TOP 1 tma2.analysisid
FROM Catalytic_tbl_Model_Analysis tma2
WHERE tma2.imscontrol = a.controlno)
LEFT OUTER JOIN
Catalytic_tbl_RDR_Analysis rdr ON rdr.ImsControl = a.controlno
AND rdr.analysisid = (SELECT TOP 1 tma2.analysisid
FROM Catalytic_tbl_RDR_Analysis tma2
WHERE tma2.imscontrol = a.controlno)
LEFT OUTER JOIN
tblProducerContacts mnged ON mnged.producercontactguid = ProdC.ManagedBy
LEFT OUTER JOIN
lstQuoteStatusReasons r1 ON r1.id = a.QuoteStatusReasonID
WHERE
l.LineName = 'EARTHQUAKE'
AND CAST(a.EffectiveDate AS DATE) >= CAST('2017-01-01' AS DATE)
AND CAST(a.EffectiveDate AS DATE) <= CAST('2017-12-31' AS DATE)
ORDER BY
a.effectiveDate
The execution plan can be found here:
https://www.brentozar.com/pastetheplan/?id=rJawDkTx-
I ran sp_help and this is what I see:
What exactly wrong with those columns?
I dont use them in a JOIN or anything. Why such bahaviour?
Table Size:
Indexes on table tblQuotes

using a subquery as a column that's using another column in the 'where' clause

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/

Problems with Syntax?

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

Problems with Sql query join

I am struggling with a sql query. I want to include the sum from an other table.
SELECT DISTINCT
tblProject.CompanyID,
tblCompany.Name,
tblCompany.AvtalsKund,
tblProject.ProjectName,
tblProject.Estimate,
tblProject.ProjectStart,
tblProject.Deadline,
CONVERT(VARCHAR(8), tblProject.Deadline, 2) AS [YY.MM.DD] ,
tblProject.PreOffered,
tblProject.ProjectType,
tblProjectType.ProjType,
tblOrdered.FirstName + + tblOrdered.LastName as OrderedFullName,
tblProject.ProjectID,
tblProject.RegDate,
tblProject.ProjectNr,
tblProject.ProjectNr
FROM tblProject
INNER JOIN tblCompany ON tblProject.CompanyID = tblCompany.CompanyID
---> INNER JOIN (SELECT tblTimeRecord.ProjectID, SUM(CONVERT(float,replace([Hours],',','') ))
FROM tblTimeRecord group by tblTimeRecord.ProjectID) as b
ON b.ProjectID = tblProject.ProjectID
INNER JOIN tblTimeRecord ON tblTimeRecord.ProjectID = tblProject.ProjectID
INNER JOIN tblProjectType ON tblProject.ProjectType = tblProjectType.ProjTypeID
LEFT OUTER JOIN tblOrdered ON tblProject.OrderedBy = tblOrdered.OrderedID
LEFT OUTER JOIN tblRel_WorkerProject ON tblProject.ProjectID = tblRel_WorkerProject.ProjectID
LEFT OUTER JOIN tblPerson ON tblPerson.PersonID = tblRel_WorkerProject.WorkerID
LEFT OUTER JOIN tblRel_StatusWorkerProject ON tblProject.ProjectID = tblRel_StatusWorkerProject.ProjectID
I want to include this sum-block from table tblTimeRecord.
I get a sum of timerapports with this code
SELECT tblTimeRecord.ProjectID,
SUM(CONVERT(float,replace([Hours],',','') ))
FROM tblTimeRecord where ProjectID=1312 group by tblTimeRecord.ProjectID
Guess i do it in join?
Got it working with this.
SELECT DISTINCT
tblProject.ProjectID,
Summa,
tblProject.CompanyID,
tblCompany.Name,
tblCompany.AvtalsKund,
tblProject.ProjectName,
tblProject.Estimate,
tblProject.ProjectStart,
tblProject.Deadline,
CONVERT(VARCHAR(8), tblProject.Deadline, 2) AS [YY.MM.DD] ,
tblProject.PreOffered,
tblProject.ProjectType,
tblProjectType.ProjType,
tblOrdered.FirstName + + tblOrdered.LastName as OrderedFullName,
tblProject.ProjectID,
tblProject.RegDate,
tblProject.ProjectNr,
tblProject.ProjectNr
FROM tblProject
INNER JOIN tblCompany ON tblProject.CompanyID = tblCompany.CompanyID
INNER JOIN (SELECT tblTimeRecord.ProjectID, SUM(CONVERT(float,replace([Hours],',','') )) as Summa FROM tblTimeRecord group by tblTimeRecord.ProjectID) as b
ON b.ProjectID = tblProject.ProjectID
INNER JOIN tblTimeRecord ON tblTimeRecord.ProjectID = tblProject.ProjectID
INNER JOIN tblProjectType ON tblProject.ProjectType = tblProjectType.ProjTypeID
LEFT OUTER JOIN tblOrdered ON tblProject.OrderedBy = tblOrdered.OrderedID
LEFT OUTER JOIN tblRel_WorkerProject ON tblProject.ProjectID = tblRel_WorkerProject.ProjectID
LEFT OUTER JOIN tblPerson ON tblPerson.PersonID = tblRel_WorkerProject.WorkerID
LEFT OUTER JOIN tblRel_StatusWorkerProject ON tblProject.ProjectID = tblRel_StatusWorkerProject.ProjectID
There are two ways to do this.
You can use a WITH clause to create the aggregate table then join this to the main query.
Or do it this way:
SELECT m.BLAH
,m.FOO
,x.AMOUNT
FROM MAINTABLE m
LEFT JOIN
(
SELECT FOO
,SUM(AMOUNT) as AMOUNT
FROM OTHERTABLE
GROUP BY FOO
) x
ON m.FOO = x.FOO
I prefer the second way.