我有这样一个查询,其中只存在'sum(“ same”)',以避免与第一种情况写相同的条件
SELECT
CASE WHEN MonthId in (1,2,3) THEN sum(CASE WHEN @Amount = 'NETEXT' THEN NetExternalExcPcEuroBudget
WHEN @Amount = 'NETAGENCY' THEN NetAgencyIncPcEuroBudget
ELSE NetAgencyIncPcEuroBudget + NetExternalExcPcEuroBudget
END
)END AS Q1,
CASE WHEN MonthId in (4,5,6) THEN sum("same")END AS Q2,
CASE WHEN MonthId in (7,8,9) THEN sum("same")END AS Q3,
CASE WHEN MonthId in (10,11,12) THEN sum("same")END AS Q4,
monthId,
RefYearId AS Year
FROM [dbo].[FactMonthlyConfirmationDashboard]
我想避免使用第二个CASE WHEN子条件,我想我可以使用联接吗?怎么做?我只想打电话给Sub-Case When。
答案 0 :(得分:0)
您可以使用CTE进行定义,然后在查询中使用它:
;with amount as (
select monthId, RefYearId AS Year, CASE WHEN @Amount = 'NETEXT' THEN NetExternalExcPcEuroBudget
WHEN @Amount = 'NETAGENCY' THEN NetAgencyIncPcEuroBudget
ELSE NetAgencyIncPcEuroBudget + NetExternalExcPcEuroBudget
END amount
from [dbo].[FactMonthlyConfirmationDashboard]
)
SELECT CASE WHEN MonthId in (1,2,3) THEN sum(amount.amount)END AS Q1,
CASE WHEN MonthId in (4,5,6) THEN sum(amount.amount)END AS Q2,
CASE WHEN MonthId in (7,8,9) THEN sum(amount.amount)END AS Q3,
CASE WHEN MonthId in (10,11,12) THEN sum(amount.amount)END AS Q4,
monthId,
RefYearId AS Year
FROM [dbo].[FactMonthlyConfirmationDashboard]
inner join amount on [FactMonthlyConfirmationDashboard].monthId = amount.monthId and [FactMonthlyConfirmationDashboard].RefYearId = amount.year
group by FactMonthlyConfirmationDashboard.monthId, FactMonthlyConfirmationDashboard.RefYearId;