将case语句结果存储在变量SQL SEVER中

时间:2017-09-13 09:31:21

标签: sql sql-server variables

无论如何都要将case语句的结果存储在一个变量中,以便它具有一个我可以在任何时候返回的固定结果。

e.g。

    CASE 
    WHEN MONTH([DATE]) = MONTH(getdate()) AND
    YEAR([DATE]) = YEAR(getdate())
    THEN SUM(Figure)
    OVER (PARTITION BY [Name], 
    MONTH([DATE])) 
    ELSE 0 
    END INTO @MTD

理想情况下,我希望能够返回一个合并的月份到日期值,其中计算不受where子句的影响

3 个答案:

答案 0 :(得分:1)

如果您使用变量来存储利润,它只能存储一行,因此您应该添加一个where子句来选择您想要的特定[名称],[月]和可能[年]检索整体利润。您应该将[Year]添加到您的分区以及WHERE子句中,除非您想要在不同年份的同一个月汇总利润。

结果代码如下:

declare
    @val int = 0;

select     
    @val = CASE 
        WHEN MONTH([DATE]) = MONTH(getdate()) AND
        YEAR([DATE]) = YEAR(getdate())
        THEN SUM(PROFIT)
        OVER (PARTITION BY [Name], 
            MONTH([DATE]), YEAR([DATE])) 
        ELSE 0 
        END 
FROM table_name
WHERE [Name] = @Name AND
      MONTH([DATE]) = @Month AND
      YEAR([DATE]) = @Year

print @val

答案 1 :(得分:0)

您可以尝试这样:

declare
  @MTD varchar(100) = null;

select 
  @MTD = CASE 
    WHEN MONTH([DATE]) = MONTH(getdate()) AND
    YEAR([DATE]) = YEAR(getdate())
    THEN SUM(PROFIT)
    OVER (PARTITION BY [Name], 
    MONTH([DATE])) 
    ELSE 0 
    END

答案 2 :(得分:0)

试试这个:

declare
  @val int = 0;

select 
  @val = CASE 
    WHEN MONTH([DATE]) = MONTH(getdate()) AND
    YEAR([DATE]) = YEAR(getdate())
    THEN SUM(isnull(PROFIT,0))
    OVER (PARTITION BY [Name], 
    MONTH([DATE])) 
    ELSE 0 
    END
    from table_name

    print @val