子案例时避免多种情况

问题描述 投票:0回答:1

我有这个查询,其中'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子条件,我想我可以使用连接?怎么办?我想只调用一次子案例。

sql-server case-when
1个回答
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;
© www.soinside.com 2019 - 2024. All rights reserved.