1
以下是我當前的查詢,我有一個CTE,用於計算由診所分組的每個會計期間的收入及其各自的交易。隨後是一個查詢,查看個人診所的工作日,並根據預期的天數找出每日平均值(計算當前日期)和預計收入。在同一查詢中使用上一年的數據
該查詢可以正常工作;但是我需要添加更多的列。我還想顯示前一年的收入情況,所以在這種情況下,我已將查詢限制爲僅顯示2016年和第9期,上一年的收入應顯示在2015年期間9,並且還需要查看上一年的日期(我想這將是一個類似的過程)。
WITH CTE_Revenue AS(
SELECT c.Clinic,
c.ClinicID,
SUM(td.Amount)*-1 AS Revenue,
p.PeriodID,
p.FiscalYear
FROM Trans.TransactionHeader th
JOIN Clinic.[Master] c
ON (th.ClinicID = c.ClinicID)
JOIN Trans.TransactionDetail td
ON (th.ClinicID = td.ClinicID AND th.TranNum = td.TranNum)
JOIN Clinic.EOD e
ON (th.ClinicID = e.ClinicID AND th.TranNum BETWEEN e.StartTran AND e.EndTran)
JOIN Clinic.Period p
ON (CAST(e.TimeRan AS date) BETWEEN p.PeriodStart AND p.PeriodEnd)
AND th.Impacts='C'
GROUP BY c.Clinic, c.ClinicID, p.PeriodID, p.FiscalYear)
SELECT w.Clinic,
w.Revenue,
(w.Revenue/days.CurrentDays) AS DailyAverage,
(w.Revenue/days.CurrentDays)*d.PeriodDays AS ProjectedRevenue
FROM CTE_Revenue w
JOIN Clinic.Dates d
ON (w.ClinicID = d.ClinicID AND w.PeriodID = d.PeriodID AND w.FiscalYear = d.FiscalYear)
JOIN ( SELECT DISTINCT
td.ClinicID,
COUNT(DISTINCT td.DateEntered) AS CurrentDays,
p.PeriodID,
p.FiscalYear
FROM Trans.TransactionDetail td
JOIN Clinic.Period p
ON td.DateEntered BETWEEN p.PeriodStart AND p.PeriodEnd
GROUP BY td.ClinicID, p.PeriodID, p.FiscalYear) AS days
ON (w.ClinicID = days.ClinicID AND w.PeriodID=days.PeriodID AND w.FiscalYear = days.FiscalYear)
WHERE w.FiscalYear = 2016
AND w.PeriodID = 9
導致SELECT語句的結束,我想,會是這個樣子:
SELECT w.Clinic,
w.Revenue,
(w.Revenue/days.CurrentDays) AS DailyAverage,
(w.Revenue/days.CurrentDays)*d.PeriodDays AS ProjectedRevenue,
PrevYear.Revenue,
(PrevYear.Revenue/PrevYear.CurrentDays) AS PYDailyAverage,
(PrevYear.Revenue/PrevYear.CurrentDays)*d.PeriodDays AS PYCalculated
此查詢可能無法得到全面優化,我還是相當新的SQL。感謝您提前提供任何建議和幫助!
編輯:下面是使用SQL Server圖中的表結構和關係的圖像:
這將工作得很好,謝謝你的洞察 –
快樂 幫助! @OMAsphyxiate – SqlZim
什麼是最好的方法來調整這個地方,它不僅限於2016/2015年,而是將前一年的數據應用於您從最終SELECT語句看的年份 –