Sql server 2008 tsql-我可以在CASE语句中执行此操作吗?

Sql server 2008 tsql-我可以在CASE语句中执行此操作吗?,sql-server-2008,tsql,case,common-table-expression,Sql Server 2008,Tsql,Case,Common Table Expression,我有两个结果集,如下所示: @四舍五入 PortfolioID Duration AAA -0.1 @最终输出 ReportingDate FundCode Sector Rank Duration Weight 31/07/2013 AAA Sector1 1 0 33.5 31/07/2013 AAA Sector2 2 0.9

我有两个结果集,如下所示:

@四舍五入

PortfolioID Duration
AAA     -0.1
@最终输出

ReportingDate   FundCode    Sector      Rank    Duration    Weight
31/07/2013      AAA         Sector1     1       0           33.5
31/07/2013      AAA         Sector2     2       0.9         29.6
31/07/2013      AAA         Sector3     3       0.6         17.3
31/07/2013      AAA         Sector4     4       0.8         11.8
31/07/2013      AAA         Sector5     5       0.1         3.1
31/07/2013      AAA         Sector6     6       0.1         1.3
31/07/2013      AAA         Sector7     7       0           0.4
31/07/2013      AAA         Sector8     8       -0.9        0
31/07/2013      AAA         Sector9     11      0           -1.3
31/07/2013      AAA         Sector10    100     0           2.8
31/07/2013      AAA         Sector11    101     0           1.5
31/07/2013      AAA         Total       102     1.6         100
我需要做的是从排名1和排名102的持续时间中减去@Rounding中的持续时间,但是如果排名1是Sector1,那么我需要从排名2中减去它。这在案例陈述中可能吗?我已经创建了下面的内容,但是我想不出如何满足Sector1永远不会被减去的情况,如果它是排名1的话

    SELECT 
        ReportingDate
    ,   FundCode
    ,   Sector
    ,   [Rank]

    ,   CASE
            WHEN [Rank] IN (1,102) THEN [Duration Contribution] - RD1.Duration
            ELSE [Duration Contribution]

        END     AS [Duration Contribution]

    ,   CASE 
            WHEN [Rank] IN (1,102) THEN Percentage - RD.[Weight]
            ELSE Percentage

        END     AS Percentage

    FROM CTE AS CTE

        INNER JOIN @RoundingDifference AS RD  -- Portfolio Weight Rounding
            ON RD.PortfolioID = CTE.FundCode

        INNER JOIN @RoundingDifferenceDur AS RD1 -- Duration Contribution Rounding
            ON RD1.PortfolioID = CTE.FundCode

    WHERE (Percentage <> 0.0
    OR [Duration Contribution] <> 0.0)

    ORDER BY    ReportingDate
            ,   FundCode
            ,   [Rank]

因此,我要寻找的结果是扇区1的持续时间仍然=0,但扇区2的持续时间和总计分别为1.0和1.7。

sql在处理集合中的行N时,不可能知道是否在行N-1中找到了特定值。这意味着,只有当排名1的记录具有特定的扇区值时,您才能真正告诉它对排名2的记录执行特殊操作

不过,您可以使用子查询检查集合中是否有秩为1的行以及扇区1

您需要使用一个详细的case语句来实现这一点,如果数据集很大,那么性能可能会很差

select
    case
        when Rank = 102
            then [Duration Contribution] - RD1.Duration
        when Rank = 1 and Sector != 'Sector1'
            then [Duration Contribution] - RD1.Duration
        when Rank = 2 and exists (select * from cte where Rank = 1 and Sector = 'Sector1')
            then [Duration Contribution - RD1.Duration
        else [Duration Contribution]
    end