I have a SQL query:
SELECT R.ResourceID,
R.EmailAddr,
CAL.Comapny_Year_Week,
CAL.Company_AP,
T.StatusCode,
SUM(T.StandardHours) AS "Total Hours"
FROM PMGB.PM.CompanyAPCalendar AS CAL
JOIN E4GB.dbo.Time AS T ON CAST(CAL.full_date AS DATE) = CAST(T.TimeEntryDate AS DATE)
JOIN E4GB.dbo.Resource AS R ON T.ResourceID = R.ResourceID
JOIN E4GB.dbo.ResourceWorkHourGroup AS WHG ON WHG.ResourceID = R.ResourceID
WHERE T.StatusCode != 'V'
AND R.EmailAddr IS NOT NULL
GROUP BY R.ResourceID,
R.EmailAddr,
CAL.Company_Year_Week,
CAL.Company_AP,
T.StatusCode;
The result of the query shows rows of data displaying user information, calendar information and SUM of Hours booked for a given Week.
When the StatusCode = 'T': I would like to SUM the SUM(T.StandardHours) WITH SUM(T.StandardHours) WHERE StatusCode = 'A' For any rows that share the same Company_Year_Week.
For example: If the Company_Year_Week = '2021 Wk24' has 2 rows of data that share the same value for this field then the Total Hours column should be the SUM(SUM(T.StandardHours) WHERE T.StatusCode = 'T', SUM(T.StandardHours) WHERE T.StatusCode = 'A').
How can I achieve this?
I tried removing the SUM T.StandardHours and using subqueries. Nothing I try seems to provide a solution to the problem I have.
1条答案
按热度按时间gorkyyrv1#
I would start by writing a query that uses just the
CompanyAPCalendar
andTime
tables, to get the sum you are looking for at a high level (essentially what will go inside an inner query, or a cross / outer apply) and then build it up from thereWithout understanding / knowing anything about your tables / data, I would guess something like this is what you might be looking for: