我有以下查询。它提取发票和时间条目,并按月计算每个客户的 EHR(有效小时费率)。我需要得到的是:
company ,agreement ,lastMonthEHR,60dayEHR,90dayEHR,6MoEHR,12MoEHR,LifeEHR
CompanyA,AgreementB, 30.45, 27.76, 55.22, 30.75, 30.00, 25.00
编辑:
我为格式道歉。我会看看我是否可以更好地格式化它。以下查询返回计算 EHR 的月度发票。
SELECT a.AGR_Name, AGR_Type.AGR_Type_Desc, c.Company_Name, ap.InvoiceDate,ap.Revenue,ap.Hours,ap.EHR
FROM AGR_Header AS a INNER JOIN Company AS c ON a.Company_RecID = c.Company_RecID
LEFT JOIN AGR_Type ON a.AGR_Type_RecID = AGR_Type.AGR_Type_RecID
LEFT JOIN (
SELECT ar.AGR_Header_RecID,ar.Revenue,ac.InvoiceDate,ISNULL (ac.Hours, 0) AS Hours,
CASE
WHEN ac.Hours IS NULL THEN (ar.Revenue)
WHEN ac.Hours <= 1 THEN (ar.Revenue)
ELSE CAST (ar.Revenue / NULLIF (ac.Hours,0) as NUMERIC (9,2))
END AS 'EHR'
FROM (
SELECT ah.AGR_Header_RecID,
DATEADD(month,ai.Month_Nbr-1,dateadd(year,ai.Year_Nbr-2000,'2000-01-01')) as InvoiceDate,
CAST (ai.Monthly_Inv_Amt AS NUMERIC (9, 2)) AS Revenue
FROM
dbo.AGR_Header AS ah INNER JOIN
dbo.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,SUM(te.Hours_Actual) AS Hours, dateadd(month, datediff(month,0,te.Date_start),0) as InvoiceDate
FROM
dbo.Time_Entry AS te INNER JOIN
dbo.AGR_Header AS ah ON te.Agr_Header_RecID = ah.AGR_Header_RecID
WHERE (te.Agr_Header_RecID IS NOT NULL) AND (te.Agr_Hours IS NOT NULL)
GROUP BY ah.AGR_Header_RecID, dateadd(month, datediff(month,0,te.Date_Start),0)) AS ac ON ar.AGR_Header_RecID = ac.AGR_Header_RecID
AND ar.InvoiceDate = ac.InvoiceDate) AS ap ON ap.AGR_Header_RecID = a.AGR_Header_RecID
ORDER BY Company, Agreement, InvoiceDate