Stop to bring duplicate results based in a condition - sql-server-2008

Even though my query is behaving the way it should be, I have an issue in the records that I can't fix in the database.
So, I want to fix it in the query.
The issue is: as the image attached, for one specific customer, there are duplicate IDs due to the Sales Person being different.
I need to bring just one result for these IDs, doesn't matter the salesperson.
I've tried:
SELECT
CONCAT(al.agr_header_recid, '-', ap.month, '-', ap.year) AS id,
al.Company_Name,
ah.AGR_Name,
al.agr_type_desc,
al.Valid_flag,
CAST(al.DateStart AS DATE) AS date_start,
CAST(al.DateEND AS DATE) AS date_end,
al.Billing_Cycle_Desc AS billing_cycle,
al.Billing_Amount,
al.Agreement_Status,
o.Owner_Level_Name AS 'Sales Person',
CASE
WHEN ah.PP_Time_Flag = 'True'
AND ah.PP_Expenses_Flag = 'False'
AND ah.PP_Products_Flag = 'False' THEN 'Time'
WHEN ah.PP_Time_Flag = 'True'
AND ah.PP_Expenses_Flag = 'True'
AND ah.PP_Products_Flag = 'False' THEN 'Time & Expenses'
WHEN ah.PP_Time_Flag = 'True'
AND ah.PP_Expenses_Flag = 'True'
AND ah.PP_Products_Flag = 'True' THEN 'Time, Products, & Expenses'
WHEN ah.PP_Time_Flag = 'True'
AND ah.PP_Expenses_Flag = 'False'
AND ah.PP_Products_Flag = 'True' THEN 'Time & Products'
WHEN ah.PP_Time_Flag = 'False'
AND ah.PP_Expenses_Flag = 'True'
AND ah.PP_Products_Flag = 'False' THEN 'Expenses'
WHEN ah.PP_Time_Flag = 'False'
AND ah.PP_Expenses_Flag = 'True'
AND ah.PP_Products_Flag = 'True' THEN 'Products & Expenses'
WHEN ah.PP_Time_Flag = 'False'
AND ah.PP_Expenses_Flag = 'False'
AND ah.PP_Products_Flag = 'True' THEN 'Products'
ELSE NULL
END AS agreement_covers_list
,CASE ah.AGR_NoEnd_Flag
WHEN 1 THEN 'Yes'
ELSE 'No'
END AS no_end_flag
,COALESCE(ap.Rev, 0) + COALESCE(child.rev, 0) AS total_revenue
,CAST(ap.Agr_Date_inv AS DATE) AS date_agreement_invoiced
,COALESCE(ap.Hours, 0) + COALESCE(child.hours, 0) AS total_agreement_hours
,COALESCE(ap.labor_Cost, 0) + COALESCE(child.labor_Cost, 0) AS total_labor_cost
,COALESCE(ap.prod_cost, 0) + COALESCE(child.prod_cost, 0) AS total_addition_cost
,CAST(CASE WHEN child.parent_recid IS NULL THEN 0 ELSE 1 END AS bit) AS has_child_agreement
,child.child_agreeements
,child.child_agreeement_types
,child.count AS number_of_child_agreements
,child.rev AS child_revenue
,ap.Rev AS parent_revenue
,ap.Hours AS parent_hours
,child.hours AS child_Hours
,ap.labor_Cost AS parent_labor_cost
,child.labor_Cost AS child_labor_cost
,ap.prod_cost AS parent_addition_cost
,child.prod_cost AS child_addition_cost
,COALESCE(ap.labor_Cost, 0) + COALESCE(child.labor_Cost, 0) + COALESCE(ap.prod_cost, 0)
+ COALESCE(child.prod_cost, 0) AS total_cost
,CASE
WHEN (COALESCE(ap.hours, 0) + COALESCE(child.hours, 0)) = 0 THEN NULL
ELSE (COALESCE(ap.rev, 0) + COALESCE(child.rev, 0))/(COALESCE(ap.hours, 0) + COALESCE(child.hours, 0))
END AS total_all_ehr
,CASE
WHEN (COALESCE(ap.hours, 0) + COALESCE(child.hours, 0)) = 0 THEN NULL
ELSE ((COALESCE(ap.rev, 0) + COALESCE(child.rev, 0)) - (COALESCE(ap.prod_cost, 0) + COALESCE(child.prod_cost, 0)))
/(COALESCE(ap.hours, 0) + COALESCE(child.hours, 0))
END AS total_no_addition_cost_ehr
,CASE
WHEN (COALESCE(ap.hours, 0)) = 0 THEN NULL
ELSE (COALESCE(ap.rev, 0))/(COALESCE(ap.hours, 0))
END AS parent_all_ehr
,CASE
WHEN (COALESCE(ap.hours, 0)) = 0 THEN NULL
ELSE (COALESCE(ap.rev, 0) - COALESCE(ap.prod_cost, 0))/(COALESCE(ap.hours, 0))
END AS parent_no_addition_cost_ehr
,CASE
WHEN (COALESCE(child.hours, 0)) = 0 THEN NULL
ELSE (COALESCE(child.rev, 0) - COALESCE(child.prod_cost, 0))/(COALESCE(child.hours, 0))
END AS child_no_addition_cost_ehr
,CASE
WHEN (COALESCE(child.hours, 0)) = 0 THEN NULL
ELSE (COALESCE(child.rev, 0))/(COALESCE(child.hours, 0))
END AS child_all_ehr
,(COALESCE(ap.rev, 0) + COALESCE(child.rev, 0))
- (COALESCE(ap.labor_Cost, 0) + COALESCE(child.labor_Cost, 0) + COALESCE(ap.prod_cost, 0) + COALESCE(child.prod_cost, 0))
AS total_agreement_margin
,CASE
WHEN (COALESCE(ap.rev, 0) + COALESCE(child.rev, 0)) = 0 THEN 0
ELSE ((COALESCE(ap.rev, 0) + COALESCE(child.rev, 0))
- (COALESCE(ap.labor_Cost, 0) + COALESCE(child.labor_Cost, 0) + COALESCE(ap.prod_cost, 0)
+ COALESCE(child.prod_cost, 0)))
/ ((COALESCE(ap.rev, 0) + COALESCE(child.rev, 0)))
END AS total_agreement_margin_percentage
FROM AGR_Header AS ah
INNER JOIN v_rpt_AgreementList AS al ON ah.AGR_Header_RecID = al.AGR_Header_RecID
INNER JOIN (SELECT
Company_RecID,
territory_recid
FROM Billing_Log
GROUP BY Company_RecID, territory_recid) AS bl ON ah.Company_RecID = bl.Company_RecID
INNER JOIN Owner_Level AS o ON bl.territory_recid = o.Owner_Level_RecID
INNER JOIN (SELECT ar.AGR_Header_RecID
,ar.Month
,ar.Year
,ar.Agr_Date_inv
,ar.Rev
,ac.Hours AS hours
,ac.Cost AS labor_cost
,addi.prod_cost
FROM
(SELECT ah.AGR_Header_RecID
,ai.Month_Nbr AS month
,ai.Year_Nbr AS year
,CONVERT (VARCHAR(8), ai.Year_Nbr, 120) + '-' + RIGHT ('0' + CONVERT (VARCHAR(8), ai.Month_nbr, 120), 2)
+ '-' + '01' AS agr_date_inv
,CAST(SUM(ai.Monthly_Inv_Amt - ai.Monthly_SalesTax_Amt) AS NUMERIC (18, 2)) AS rev
FROM agr_header AS ah
INNER JOIN agr_invoice_amt AS ai ON ah.AGR_Header_RecID = ai.AGR_Header_RecID
GROUP BY ah.AGR_Header_RecID
,ai.Month_Nbr
,ai.Year_Nbr) AS ar
LEFT JOIN
(SELECT ah.AGR_Header_RecID
,DATEPART(MONTH, te.Date_Start) AS month
,DATEPART(YEAR, te.Date_Start) AS year
,SUM(te.AgrHrsCovered) AS hours
,CAST(SUM(te.AgrHrsCovered * te.Hourly_Cost_Decimal) AS NUMERIC (18, 2)) AS cost
FROM v_rpt_time AS te
INNER JOIN agr_header AS ah ON te.Agr_Header_RecID = ah.AGR_Header_RecID
WHERE te.date_start >= DATEADD(mm, -3, CURRENT_TIMESTAMP)
AND te.Agr_Header_RecID IS NOT NULL
AND te.AgrHrsCovered IS NOT NULL
GROUP BY ah.AGR_Header_RecID
,DATEPART(MONTH, te.Date_Start)
,DATEPART(YEAR, te.Date_Start)) AS ac ON ar.AGR_Header_RecID = ac.AGR_Header_RecID
AND ar.Month = ac.Month
AND ar.Year = ac.Year
LEFT JOIN
(SELECT SUM(vadi.Extended_Cost_Amount) AS prod_cost
,vadi.AGR_Header_RecID
,vadi.agr_month AS month
,vadi.agr_year AS year
FROM iv_product vadi
GROUP BY vadi.AGR_Header_RecID
,vadi.agr_month
,vadi.agr_year) AS addi ON addi.AGR_Header_RecID = ar.AGR_Header_RecID AND ar.year = addi.year
AND ar.month = addi.month
) AS ap ON ap.AGR_Header_RecID = al.AGR_Header_RecID
LEFT JOIN
(SELECT ar.parent_recid
,ar.Month
,ar.Year
,ar.Rev
,ac.Hours AS hours
,ac.Cost AS labor_cost
,ar.child_agreeements
,ar.count
,ar.child_agreeement_types
,addi.prod_cost
FROM
(SELECT ah.parent_recid
,ai.Month_Nbr AS month
,ai.Year_Nbr AS year
,CAST(SUM(ai.Monthly_Inv_Amt - ai.Monthly_SalesTax_Amt) AS NUMERIC (18, 2)) AS rev
,SUBSTRING(
(SELECT ', '+ahc.AGR_Name AS [text()]
FROM agr_header ahc
WHERE ahc.parent_recid = ah.parent_Recid
ORDER BY ahc.AGR_Name
For XML PATH (''))
, 2, 1000) [child_agreeements]
,SUBSTRING(
(SELECT ', '+atc.AGR_Type_Desc AS [text()]
FROM agr_header ahc2
INNER JOIN AGR_Type atc ON atc.AGR_Type_RecID = ahc2.AGR_Type_RecID
WHERE ahc2.parent_recid = ah.parent_Recid
ORDER BY atc.AGR_Type_Desc
For XML PATH (''))
, 2, 1000) [child_agreeement_types]
,COUNT(1) AS count
FROM agr_header AS ah
INNER JOIN agr_invoice_amt AS ai ON ah.AGR_Header_RecID = ai.AGR_Header_RecID
GROUP BY ah.parent_Recid
,ai.Month_Nbr
,ai.Year_Nbr) AS ar
LEFT JOIN
(SELECT ah.parent_Recid
,DATEPART(MONTH, te.Date_Start) AS month
,DATEPART(YEAR, te.Date_Start) AS year
,SUM(te.AgrHrsCovered) AS hours
,CAST(SUM(te.AgrHrsCovered * te.Hourly_Cost_Decimal) AS NUMERIC (18, 2)) AS cost
FROM v_rpt_time AS te
INNER JOIN agr_header AS ah ON te.Agr_Header_RecID = ah.AGR_Header_RecID
WHERE te.date_start >= DATEADD(mm, -6, CURRENT_TIMESTAMP)
AND te.Agr_Header_RecID IS NOT NULL
AND te.AgrHrsCovered IS NOT NULL
GROUP BY ah.parent_Recid
,DATEPART(MONTH, te.Date_Start)
,DATEPART(YEAR, te.Date_Start)) AS ac ON ar.parent_recid = ac.parent_recid AND ar.Month = ac.Month
AND ar.Year = ac.Year
LEFT JOIN
(SELECT SUM(vadi.Extended_Cost_Amount) AS prod_cost
,ahp.parent_Recid
,vadi.agr_month AS month
,vadi.agr_year AS year
FROM agr_header ahp
INNER JOIN iv_product vadi ON vadi.AGR_Header_RecID = ahp.AGR_Header_RecID
GROUP BY ahp.parent_Recid
,vadi.agr_month
,vadi.agr_year) AS addi ON addi.parent_Recid = ar.parent_Recid AND ar.year = addi.year AND ar.month = addi.month
) AS child ON child.parent_recid = al.AGR_Header_RecID AND child.month = ap.month AND child.year = ap.year
WHERE ah.parent_Recid IS NULL
AND ap.agr_date_inv > DATEADD(YEAR, -2, CURRENT_TIMESTAMP)
AND ap.agr_date_inv <= CURRENT_TIMESTAMP
AND o.Owner_Level_Name IN ('Australia', 'Alex', 'Adam')
AND al.Agreement_Status = 'active'
AND al.Company_Name = 'Client A'
But it's not working.
This is the outcome (not pasting all the columns here) and a picture could be useful due the formating, its attached in the end:
id Company_Name AGR_Name agr_type_desc Valid_flag date_start date_end billing_cycle Billing_Amount Agreement_Status Sales Person
464-2-2022 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Adam
464-2-2022 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Alex
464-6-2021 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Adam
464-6-2021 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Alex
464-10-2020 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Adam
464-10-2020 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Alex
464-4-2021 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Adam
464-4-2021 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Alex
464-8-2020 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Adam
464-8-2020 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Alex
464-11-2021 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Adam
464-11-2021 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Alex
464-3-2021 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Adam
464-3-2021 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Alex
464-7-2020 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Adam
464-7-2020 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Alex
464-4-2022 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Adam
464-4-2022 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Alex
464-1-2021 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Adam
464-1-2021 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Alex
464-8-2021 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Adam
464-8-2021 Client A Client A - BaaS Service - User Master Services Agreement 1 1/06/2020 NULL Monthly 150 Active Alex
query outcome

Basically, I have used the function ROW_NUMBER, as shown in the line before your "id" column.
In case you do not want to show the "row number column" or "rn" in the results, you can replace the * in the following query, SELECT * FROM TMP WHERE rnk = 1 to every column name you have previously mentioned except "rn".
Let me know if this works for you.
WITH TMP AS (
SELECT
ROW_NUMBER() OVER(PARTITION BY CONCAT(al.agr_header_recid, '-', ap.month, '-', ap.year) ORDER BY o.Owner_Level_Name) as rn,
CONCAT(al.agr_header_recid, '-', ap.month, '-', ap.year) AS id,
al.Company_Name,
ah.AGR_Name,
al.agr_type_desc,
al.Valid_flag,
CAST(al.DateStart AS DATE) AS date_start,
CAST(al.DateEND AS DATE) AS date_end,
al.Billing_Cycle_Desc AS billing_cycle,
al.Billing_Amount,
al.Agreement_Status,
o.Owner_Level_Name AS 'Sales Person',
CASE
WHEN ah.PP_Time_Flag = 'True'
AND ah.PP_Expenses_Flag = 'False'
AND ah.PP_Products_Flag = 'False' THEN 'Time'
WHEN ah.PP_Time_Flag = 'True'
AND ah.PP_Expenses_Flag = 'True'
AND ah.PP_Products_Flag = 'False' THEN 'Time & Expenses'
WHEN ah.PP_Time_Flag = 'True'
AND ah.PP_Expenses_Flag = 'True'
AND ah.PP_Products_Flag = 'True' THEN 'Time, Products, & Expenses'
WHEN ah.PP_Time_Flag = 'True'
AND ah.PP_Expenses_Flag = 'False'
AND ah.PP_Products_Flag = 'True' THEN 'Time & Products'
WHEN ah.PP_Time_Flag = 'False'
AND ah.PP_Expenses_Flag = 'True'
AND ah.PP_Products_Flag = 'False' THEN 'Expenses'
WHEN ah.PP_Time_Flag = 'False'
AND ah.PP_Expenses_Flag = 'True'
AND ah.PP_Products_Flag = 'True' THEN 'Products & Expenses'
WHEN ah.PP_Time_Flag = 'False'
AND ah.PP_Expenses_Flag = 'False'
AND ah.PP_Products_Flag = 'True' THEN 'Products'
ELSE NULL
END AS agreement_covers_list
,CASE ah.AGR_NoEnd_Flag
WHEN 1 THEN 'Yes'
ELSE 'No'
END AS no_end_flag
,COALESCE(ap.Rev, 0) + COALESCE(child.rev, 0) AS total_revenue
,CAST(ap.Agr_Date_inv AS DATE) AS date_agreement_invoiced
,COALESCE(ap.Hours, 0) + COALESCE(child.hours, 0) AS total_agreement_hours
,COALESCE(ap.labor_Cost, 0) + COALESCE(child.labor_Cost, 0) AS total_labor_cost
,COALESCE(ap.prod_cost, 0) + COALESCE(child.prod_cost, 0) AS total_addition_cost
,CAST(CASE WHEN child.parent_recid IS NULL THEN 0 ELSE 1 END AS bit) AS has_child_agreement
,child.child_agreeements
,child.child_agreeement_types
,child.count AS number_of_child_agreements
,child.rev AS child_revenue
,ap.Rev AS parent_revenue
,ap.Hours AS parent_hours
,child.hours AS child_Hours
,ap.labor_Cost AS parent_labor_cost
,child.labor_Cost AS child_labor_cost
,ap.prod_cost AS parent_addition_cost
,child.prod_cost AS child_addition_cost
,COALESCE(ap.labor_Cost, 0) + COALESCE(child.labor_Cost, 0) + COALESCE(ap.prod_cost, 0)
+ COALESCE(child.prod_cost, 0) AS total_cost
,CASE
WHEN (COALESCE(ap.hours, 0) + COALESCE(child.hours, 0)) = 0 THEN NULL
ELSE (COALESCE(ap.rev, 0) + COALESCE(child.rev, 0))/(COALESCE(ap.hours, 0) + COALESCE(child.hours, 0))
END AS total_all_ehr
,CASE
WHEN (COALESCE(ap.hours, 0) + COALESCE(child.hours, 0)) = 0 THEN NULL
ELSE ((COALESCE(ap.rev, 0) + COALESCE(child.rev, 0)) - (COALESCE(ap.prod_cost, 0) + COALESCE(child.prod_cost, 0)))
/(COALESCE(ap.hours, 0) + COALESCE(child.hours, 0))
END AS total_no_addition_cost_ehr
,CASE
WHEN (COALESCE(ap.hours, 0)) = 0 THEN NULL
ELSE (COALESCE(ap.rev, 0))/(COALESCE(ap.hours, 0))
END AS parent_all_ehr
,CASE
WHEN (COALESCE(ap.hours, 0)) = 0 THEN NULL
ELSE (COALESCE(ap.rev, 0) - COALESCE(ap.prod_cost, 0))/(COALESCE(ap.hours, 0))
END AS parent_no_addition_cost_ehr
,CASE
WHEN (COALESCE(child.hours, 0)) = 0 THEN NULL
ELSE (COALESCE(child.rev, 0) - COALESCE(child.prod_cost, 0))/(COALESCE(child.hours, 0))
END AS child_no_addition_cost_ehr
,CASE
WHEN (COALESCE(child.hours, 0)) = 0 THEN NULL
ELSE (COALESCE(child.rev, 0))/(COALESCE(child.hours, 0))
END AS child_all_ehr
,(COALESCE(ap.rev, 0) + COALESCE(child.rev, 0))
- (COALESCE(ap.labor_Cost, 0) + COALESCE(child.labor_Cost, 0) + COALESCE(ap.prod_cost, 0) + COALESCE(child.prod_cost, 0))
AS total_agreement_margin
,CASE
WHEN (COALESCE(ap.rev, 0) + COALESCE(child.rev, 0)) = 0 THEN 0
ELSE ((COALESCE(ap.rev, 0) + COALESCE(child.rev, 0))
- (COALESCE(ap.labor_Cost, 0) + COALESCE(child.labor_Cost, 0) + COALESCE(ap.prod_cost, 0)
+ COALESCE(child.prod_cost, 0)))
/ ((COALESCE(ap.rev, 0) + COALESCE(child.rev, 0)))
END AS total_agreement_margin_percentage
FROM AGR_Header AS ah
INNER JOIN v_rpt_AgreementList AS al ON ah.AGR_Header_RecID = al.AGR_Header_RecID
INNER JOIN (SELECT
Company_RecID,
territory_recid
FROM Billing_Log
GROUP BY Company_RecID, territory_recid) AS bl ON ah.Company_RecID = bl.Company_RecID
INNER JOIN Owner_Level AS o ON bl.territory_recid = o.Owner_Level_RecID
INNER JOIN (SELECT ar.AGR_Header_RecID
,ar.Month
,ar.Year
,ar.Agr_Date_inv
,ar.Rev
,ac.Hours AS hours
,ac.Cost AS labor_cost
,addi.prod_cost
FROM
(SELECT ah.AGR_Header_RecID
,ai.Month_Nbr AS month
,ai.Year_Nbr AS year
,CONVERT (VARCHAR(8), ai.Year_Nbr, 120) + '-' + RIGHT ('0' + CONVERT (VARCHAR(8), ai.Month_nbr, 120), 2)
+ '-' + '01' AS agr_date_inv
,CAST(SUM(ai.Monthly_Inv_Amt - ai.Monthly_SalesTax_Amt) AS NUMERIC (18, 2)) AS rev
FROM agr_header AS ah
INNER JOIN agr_invoice_amt AS ai ON ah.AGR_Header_RecID = ai.AGR_Header_RecID
GROUP BY ah.AGR_Header_RecID
,ai.Month_Nbr
,ai.Year_Nbr) AS ar
LEFT JOIN
(SELECT ah.AGR_Header_RecID
,DATEPART(MONTH, te.Date_Start) AS month
,DATEPART(YEAR, te.Date_Start) AS year
,SUM(te.AgrHrsCovered) AS hours
,CAST(SUM(te.AgrHrsCovered * te.Hourly_Cost_Decimal) AS NUMERIC (18, 2)) AS cost
FROM v_rpt_time AS te
INNER JOIN agr_header AS ah ON te.Agr_Header_RecID = ah.AGR_Header_RecID
WHERE te.date_start >= DATEADD(mm, -3, CURRENT_TIMESTAMP)
AND te.Agr_Header_RecID IS NOT NULL
AND te.AgrHrsCovered IS NOT NULL
GROUP BY ah.AGR_Header_RecID
,DATEPART(MONTH, te.Date_Start)
,DATEPART(YEAR, te.Date_Start)) AS ac ON ar.AGR_Header_RecID = ac.AGR_Header_RecID
AND ar.Month = ac.Month
AND ar.Year = ac.Year
LEFT JOIN
(SELECT SUM(vadi.Extended_Cost_Amount) AS prod_cost
,vadi.AGR_Header_RecID
,vadi.agr_month AS month
,vadi.agr_year AS year
FROM iv_product vadi
GROUP BY vadi.AGR_Header_RecID
,vadi.agr_month
,vadi.agr_year) AS addi ON addi.AGR_Header_RecID = ar.AGR_Header_RecID AND ar.year = addi.year
AND ar.month = addi.month
) AS ap ON ap.AGR_Header_RecID = al.AGR_Header_RecID
LEFT JOIN
(SELECT ar.parent_recid
,ar.Month
,ar.Year
,ar.Rev
,ac.Hours AS hours
,ac.Cost AS labor_cost
,ar.child_agreeements
,ar.count
,ar.child_agreeement_types
,addi.prod_cost
FROM
(SELECT ah.parent_recid
,ai.Month_Nbr AS month
,ai.Year_Nbr AS year
,CAST(SUM(ai.Monthly_Inv_Amt - ai.Monthly_SalesTax_Amt) AS NUMERIC (18, 2)) AS rev
,SUBSTRING(
(SELECT ', '+ahc.AGR_Name AS [text()]
FROM agr_header ahc
WHERE ahc.parent_recid = ah.parent_Recid
ORDER BY ahc.AGR_Name
For XML PATH (''))
, 2, 1000) [child_agreeements]
,SUBSTRING(
(SELECT ', '+atc.AGR_Type_Desc AS [text()]
FROM agr_header ahc2
INNER JOIN AGR_Type atc ON atc.AGR_Type_RecID = ahc2.AGR_Type_RecID
WHERE ahc2.parent_recid = ah.parent_Recid
ORDER BY atc.AGR_Type_Desc
For XML PATH (''))
, 2, 1000) [child_agreeement_types]
,COUNT(1) AS count
FROM agr_header AS ah
INNER JOIN agr_invoice_amt AS ai ON ah.AGR_Header_RecID = ai.AGR_Header_RecID
GROUP BY ah.parent_Recid
,ai.Month_Nbr
,ai.Year_Nbr) AS ar
LEFT JOIN
(SELECT ah.parent_Recid
,DATEPART(MONTH, te.Date_Start) AS month
,DATEPART(YEAR, te.Date_Start) AS year
,SUM(te.AgrHrsCovered) AS hours
,CAST(SUM(te.AgrHrsCovered * te.Hourly_Cost_Decimal) AS NUMERIC (18, 2)) AS cost
FROM v_rpt_time AS te
INNER JOIN agr_header AS ah ON te.Agr_Header_RecID = ah.AGR_Header_RecID
WHERE te.date_start >= DATEADD(mm, -6, CURRENT_TIMESTAMP)
AND te.Agr_Header_RecID IS NOT NULL
AND te.AgrHrsCovered IS NOT NULL
GROUP BY ah.parent_Recid
,DATEPART(MONTH, te.Date_Start)
,DATEPART(YEAR, te.Date_Start)) AS ac ON ar.parent_recid = ac.parent_recid AND ar.Month = ac.Month
AND ar.Year = ac.Year
LEFT JOIN
(SELECT SUM(vadi.Extended_Cost_Amount) AS prod_cost
,ahp.parent_Recid
,vadi.agr_month AS month
,vadi.agr_year AS year
FROM agr_header ahp
INNER JOIN iv_product vadi ON vadi.AGR_Header_RecID = ahp.AGR_Header_RecID
GROUP BY ahp.parent_Recid
,vadi.agr_month
,vadi.agr_year) AS addi ON addi.parent_Recid = ar.parent_Recid AND ar.year = addi.year AND ar.month = addi.month
) AS child ON child.parent_recid = al.AGR_Header_RecID AND child.month = ap.month AND child.year = ap.year
WHERE ah.parent_Recid IS NULL
AND ap.agr_date_inv > DATEADD(YEAR, -2, CURRENT_TIMESTAMP)
AND ap.agr_date_inv <= CURRENT_TIMESTAMP
AND o.Owner_Level_Name IN ('Australia', 'Alex', 'Adam')
AND al.Agreement_Status = 'active'
AND al.Company_Name = 'Client A'
)
SELECT *
FROM TMP
WHERE rn = 1

Related

SQLSERVER Running Balance

Actually i have problem on my query to get the running balance , i have debit and credit transaction i need one column to showing the cumulative running balance this is the code i used :
Select * From (
Select D.AccNo, H.[Date], A.AccountName, H.TrxNo,
(Case When ((D.Remark = '') or (D.Remark is Null)) Then H.Trxnote Else D.Remark End) As TrxDetailDescA,
(D.Debit * 1) AS DebitValue, (D.Credit * 1) AS CreditValue,SUM(COALESCE(D.Debit, 0) - COALESCE(D.Credit, 0)) AS Balance
From TblHeadTrans H, TblTransDetails D, TblAccount A
Where H.Guid = D.[LineNo]
And D.AccNo = A.AccountNo
And H.[Date] >= '01-01-2022' And H.[Date] <= '10-07-2022' And D.AccNo >= '1003'
group by AccNo,H.[Date],A.AccountName,H.TrxNo,D.Remark,h.Trxnote,d.Debit,d.Credit
Union All
Select D.AccNo, Null As TrxDate, A.AccountName, Null As TrxNo,
'Opening Balance' As TrxDetailDesc,
Case When (Sum(D.Debit * 1) - Sum(D.Credit *1)) < 0 then 0
Else (Sum(D.Debit * 1) - Sum(D.Credit * 1)) End As DebitValue,
Case When (Sum(D.Credit * 1) - Sum(D.Debit * 1)) < 0 then 0
Else (Sum(D.Credit * 1) - Sum(D.Debit * 1)) End As CreditValue
, SUM(COALESCE(d.Debit, 0) - COALESCE(d.credit, 0)) AS Balance
From TblHeadTrans H, TblTransDetails D, TblAccount A
Where H.guid = D.[LineNo] And D.AccNo = A.AccountNo
And d.[Date] < '01-01-2022' And D.accno = '1003'
Group By D.AccNo, A.AccountName,H.Date,H.TrxNo
) ReportData
WHERE 1=1
Order By AccNo, [Date], TrxNo
and the result showing as the picture:
the result

MySql get balance of accounts

i want to calculate the balance of 3 accounts.
I have 2 tables:
accounts with id, name and start-balance
transactions with value, charge-account, type and paid
To calculate the balance i have to add the start-balance (from accounts) with alle the transaction-values where charge-account = account-id, paid = 1 and type = 1. Then i have to subtract (correct word?) all the transaction-values where charge-account = account-id, paid = 1 and type = 0
At the end, if everything would work i just want to see what balance the accounts have right now.
i tried this query but i get wrong results, it looks like it adds the start-balance multiple times...
SELECT
SUM(IF(a.id = 1, IF(t.type = 1 AND t.charge_account = 1, t.value, 0) - IF(t.type = 0 AND t.charge_account = 1, t.value, 0), 0) + a.start-balance) as "balanc_1",
SUM(IF(a.id = 2, IF(t.type = 1 AND t.charge_account = 2, t.value, 0) - IF(t.type = 0 AND t.charge_account = 2, t.value, 0), 0) + a.start-balance) as "balance_2",
SUM(IF(a.id = 3, IF(t.type = 1 AND t.charge_account = 3, t.value, 0) - IF(t.type = 0 AND t.charge_account = 3, t.value, 0), 0) + a.start-balance) as "balance_3"
FROM test.transactions t, test.accounts a
WHERE t.paid = 1;
transactions:
accounts:
how it should be like:
SELECT a.id,
MAX ( a.`start-balance` ) +
SUM ( CASE WHEN t.type = 1 then t.value
WHEN t.type = 2 then -t.value
ELSE 0
END ) as balance
FROM accounts a
JOIN transactions t
ON a.id = t.`charge-account`
WHERE a.id IN (1,2,3)
AND t.paid = 1
GROUP BY id
You need to use UNION and then group by account id
select accountid, sum(amount ) as amount from (
select accountid, startamount as amount from accounts
union
select accountid, transactionamount from transactions WHERE ....
) t
group by accountid

EMBEDDED DATEDIFF EXCLUD WEEKENDS + CASE STATEMENT

I have the below query that utilizes a case statement. I would like to datediff two dates but exclude weekend days.
I have the below that excutes but now I would like to exclude Sat and Sunday from this... AND DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate) <= 2
CASE WHEN
S.Name IN ('Assessment','Survey')
AND A.ALERT_DESC = 'ER'
AND CAST(A.ALERTS_CREATE_DT AS DATE) <= CAST(S.CreatedDate AS DATE)
AND DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate) <= 2 /*EXCLUDE Sat and Sunday from the calculation*/
Full Query
SELECT
CASE WHEN
S.Name IN ('Assessment','Survey')
AND A.ALERT_DESC = 'ER'
AND CAST(A.ALERTS_CREATE_DT AS DATE) <= CAST(S.CreatedDate AS DATE)
AND
( DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate) <= 2 /*Business Days*/
--DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate) + 1
---(DATEDIFF(WK,A.ALERTS_CREATE_DT,S.CreatedDate) * 2)
---(CASE WHEN DATENAME(DW,A.ALERTS_CREATE_DT) = 'SUNDAY' THEN 1 ELSE 0 END)
---(CASE WHEN DATENAME(DW,S.CreatedDate) = 'SATURADAY' THEN 1 ELSE 0 END)
)
THEN 'Y'
WHEN A.ALERT_DESC = 'model' OR S.CreatedDate IS NULL OR S.Name = 'ER'
THEN ''
ELSE 'N'
END 'Count towards Alerts'
FROM A
FULL S ON A.id= S.id
WHERE 1=1
This should give you the required result by excluding the Saturdays and Sundays.
SELECT A.ALERT_DESC,A.ALERTS_CREATE_DT,S.Name,S.CreatedDate,
CASE WHEN
S.Name IN ('Assessment','Survey') AND A.ALERT_DESC = 'ER'
AND CAST(A.ALERTS_CREATE_DT AS DATE) <= CAST(S.CreatedDate AS DATE)
AND
(( DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate)+1
- (datediff(wk,A.ALERTS_CREATE_DT,S.CreatedDate)*2)
- case when datepart(dw,A.ALERTS_CREATE_DT)=1 then 1 else 0 end
- case when datepart(dw,S.CreatedDate)=7 then 1 else 0 end
)) <=2 THEN 'Y'
WHEN A.ALERT_DESC = 'model' OR S.CreatedDate IS NULL OR S.Name = 'ER' THEN ''
ELSE 'N' END 'Count towards Alerts'
FROM A,S

Show the status of daily file loads from mysql database

I am working on a project where we receive some files daily which are loaded into the database, their status is recorded into meta-data.
For e.g.,
There are 2 different clients from which we get three different type of files, type_a, type_b and type_c.
CLIENT_MASTER
----------------------
client_id|client_name
1|xxx
2|yyy
File status is stored in FILE_MASTER table
FILE_MASTER
-----------------------------------
file_key|client_id|filename|status
1|1|type_a_2010-10-07.csv|12
2|1|type_b_2010-10-07.csv|12
3|1|type_c_2010-10-07.csv|12
4|2|type_a_2010-10-07.csv|12
5|2|type_b_2010-10-07.csv|12
The status keys are stored in STATUS_MASTER table
STATUS_MASTER
-------------------
status_key|status
12|Completed
I want to develop a dashboard showing status of daily file loads, in the below format -
Client|type_a|type_b|type_c
xxx|Yes|Yes|Yes
yyy|Yes|Yes|No
Any help on this would be much appreciated.
This query will return result for current date:
SELECT cm.client_name,
CASE WHEN v.type_a_count > 0 THEN 'Yes' ELSE 'No' END AS type_a,
CASE WHEN v.type_b_count > 0 THEN 'Yes' ELSE 'No' END AS type_b,
CASE WHEN v.type_c_count > 0 THEN 'Yes' ELSE 'No' END AS type_c
FROM client_master cm
LEFT OUTER JOIN (
SELECT fm.client_id,
SUBSTRING(fm.client_name, 8, 10) AS file_date,
SUM(CASE WHEN SUBSTRING(fm.client_name, 1, 6) = 'type_a' THEN 1 ELSE 0 END) AS type_a_count,
SUM(CASE WHEN SUBSTRING(fm.client_name, 1, 6) = 'type_b' THEN 1 ELSE 0 END) AS type_b_count,
SUM(CASE WHEN SUBSTRING(fm.client_name, 1, 6) = 'type_c' THEN 1 ELSE 0 END) AS type_c_count
FROM file_master fm
WHERE SUBSTRING(fm.client_name, 8, 10) = CURDATE()
AND fm.status = 12
GROUP BY fm.client_id, SUBSTRING(fm.client_name, 8, 10)
) v ON cm.client_id = v.client_id
Try this query
SELECT c.name,
IF(FIND_IN_SET('type_a', GROUP_CONCAT(SUBSTRING_INDEX(f1.filename,'_',2))), 'Yes', 'No') as type_a,
IF(FIND_IN_SET('type_b', GROUP_CONCAT(SUBSTRING_INDEX(f1.filename,'_',2))), 'Yes', 'No') as type_b,
IF(FIND_IN_SET('type_c', GROUP_CONCAT(SUBSTRING_INDEX(f1.filename,'_',2))), 'Yes', 'No') as type_c
FROM client_master c
JOIN file_master f1 ON(f1.client_id = c.client_id)
JOIN status_master sm ON(sm.status = f1.status)
WHERE sm.status='Completed' AND SUBSTRING_INDEX(f1.filename,'_',-1) = CURDATE()
GROUP BY c.id

A faster SQL Query to get this done

I have a SP and UDF that brings me Totals. But I know there is a COUNT CASE WHEN query possible to get totals in a single go. Can anyone help me in this regard? My current query is just a redundant pause.
ALTER PROCEDURE [dbo].[GetMailBasketsForLocums]
AS
BEGIN
SET NOCOUNT ON;
SET FMTONLY OFF;
SET DATEFORMAT DMY;
SELECT DISTINCT Locum.OID,
Locum.FirstName + ' ' + Locum.LastName AS Name,
dbo.GetMailBasketTotalsForLocums(MailBasket.LocumId, 1) AS BookingsConfirmed,
dbo.GetMailBasketTotalsForLocums(MailBasket.LocumId, 3) AS BookingsCancelled,
dbo.GetMailBasketTotalsForLocums(MailBasket.LocumId, 5) AS BookingsSwitched,
(dbo.GetMailBasketTotalsForLocums(MailBasket.LocumId, 1) +
dbo.GetMailBasketTotalsForLocums(MailBasket.LocumId, 3) +
dbo.GetMailBasketTotalsForLocums(MailBasket.LocumId, 5)) AS Total
FROM MailBasket INNER JOIN
Locum
ON Locum.OID = MailBasket.LocumID
WHERE MailBasket.IsSent = 0
AND MailBasket.MailTypeID IN (1, 3, 5);
END
And
ALTER FUNCTION [dbo].[GetMailBasketTotalsForLocums]
(
#LocumID BIGINT,
#MailTypeID INT
)
RETURNS int
AS
BEGIN
DECLARE #Result int
SELECT #Result = COUNT(MailBasket.OID)
FROM MailBasket
WHERE MailBasket.MailTypeID = #MailTypeID
AND MailBasket.LocumID = #LocumID
AND MailBasket.IsSent = 0;
RETURN #Result
END
Regards.
SELECT
DISTINCT Locum.OID,
Locum.FirstName + ' ' + Locum.LastName AS Name,
COUNT(CASE WHEN MailBasket.MailTypeID = 1 THEN 1 ELSE NULL END) AS BookingsConfirmed,
COUNT(CASE WHEN MailBasket.MailTypeID = 3 THEN 1 ELSE NULL END) AS BookingsCancelled,
COUNT(CASE WHEN MailBasket.MailTypeID = 5 THEN 1 ELSE NULL END) AS BookingsSwitched,
COUNT(*) AS Total
FROM
MailBasket INNER JOIN
Locum
ON Locum.OID = MailBasket.LocumID
WHERE MailBasket.IsSent = 0
AND MailBasket.MailTypeID IN (1, 3, 5);
COUNT ignores NULLs to the conditional count works
You can also use SUM
SUM(CASE WHEN MailBasket.MailTypeID = 5 THEN 1 ELSE 0 END)
Try this:
SELECT DISTINCT Locum.OID, Locum.FirstName + ' ' + Locum.LastName AS Name,
COUNT(CASE WHEN MailBasket.MailTypeID = 1 THEN MailBasket.MailTypeID END) as BookingsConfirmed,
COUNT(CASE WHEN MailBasket.MailTypeID = 3 THEN MailBasket.MailTypeID END) as BookingsCancelled,
COUNT(CASE WHEN MailBasket.MailTypeID = 5 THEN MailBasket.MailTypeID END) as BookingsSwitched,
COUNT(*) as TOTAL
FROM MailBasket INNER JOIN
Locum
ON Locum.OID = MailBasket.LocumID
WHERE MailBasket.IsSent = 0
AND MailBasket.MailTypeID IN (1, 3, 5);
You can use a case inside a sum and group on the Locum records:
select
Locum.OID,
Locum.FirstName + ' ' + Locum.LastName AS Name,
sum(case when MailBasket.MailTypeID = 1 then 1 else 0 end) as BookingsConfirmed,
sum(case when MailBasket.MailTypeID = 3 then 1 else 0 end) as BookingsCancelled,
sum(case when MailBasket.MailTypeId = 5 then 1 else 0 end) as BookingsSwitched,
count(*) as Total
from
MailBasket
inner join Locum on Locum.OID = MailBasket.LocumID
where
MailBasket.IsSent = 0
and MailBasket.MailTypeID IN (1, 3, 5)
group by
Locum.OID, Locum.FirstName, Locum.LastName