在单个查询中更新多个变量

时间:2015-12-02 07:49:10

标签: sql sql-server tsql

我有一个table每个工作日(周日到周六)的金额总和。表结构如下。

enter image description here

我需要将这些表值分配给参数。对于例如:我需要将rdate '2015-11-15'的总和,即324分配给变量@sundayval,将374分配给变量@mondayval等...

如何执行此操作在单个更新查询中。我试过Case声明, 但它只为变量@saturdayval赋值。

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

好的 - 让我们这样做:else情况设置为返回自身,因此每个变量基本上聚合为合并。注意:我现在没办法测试这个。 :)

SELECT
    @sundayval = case when DATEPART(weekday, rdate) = 1 then sum else @sundayval end
    , @mondayval = case when DATEPART(weekday, rdate) = 2 then sum else @mondayval end
    , @tuesdayval = case when DATEPART(weekday, rdate) = 3 then sum else @tuesdayval end
    , @wednesdayval = case when DATEPART(weekday, rdate) = 4 then sum else @wednesdayval end
    , @thursdayval = case when DATEPART(weekday, rdate) = 5 then sum else @thursdayval end
    , @fridayval = case when DATEPART(weekday, rdate) = 6 then sum else @fridayval end
    , @saturdayval = case when DATEPART(weekday, rdate) = 7 then sum else @saturdayval end
FROM TABLE

答案 1 :(得分:1)

这可以胜任。它并不依赖于任何特定DATEFIRST设置 - 而是使用任意选择的星期日(我今年5月17日选择)(我通常称之为"已知的好"日期因为它具有我们正在寻找的属性,在这种情况下是一周中的正确日期:

declare @t table ([sum] int not null,rdate datetime2 not null)
insert into @t([sum],rdate) values
(324,'20151115'),
(374,'20151116'),
(424,'20151117'),
(474,'20151118'),
(524,'20151119'),
(574,'20151120'),
(624,'20151121')

declare @sundayval int
declare @mondayval int
declare @tuesdayval int
declare @wednesdayval int
declare @thursdayval int
declare @fridayval int
declare @saturdayval int

select
    @sundayval    = SUM(CASE WHEN DATEPART(weekday,rdate) = DATEPART(weekday,'20150517') THEN [sum] END),
    @mondayval    = SUM(CASE WHEN DATEPART(weekday,rdate) = DATEPART(weekday,'20150518') THEN [sum] END),
    @tuesdayval   = SUM(CASE WHEN DATEPART(weekday,rdate) = DATEPART(weekday,'20150519') THEN [sum] END),
    @wednesdayval = SUM(CASE WHEN DATEPART(weekday,rdate) = DATEPART(weekday,'20150520') THEN [sum] END),
    @thursdayval  = SUM(CASE WHEN DATEPART(weekday,rdate) = DATEPART(weekday,'20150521') THEN [sum] END),
    @fridayval    = SUM(CASE WHEN DATEPART(weekday,rdate) = DATEPART(weekday,'20150522') THEN [sum] END),
    @saturdayval  = SUM(CASE WHEN DATEPART(weekday,rdate) = DATEPART(weekday,'20150523') THEN [sum] END)
from @t

select @sundayval,@mondayval,@tuesdayval,@wednesdayval,@thursdayval,@fridayval,@saturdayval

结果:

----------- ----------- ----------- ----------- ----------- ----------- -----------
324         374         424         474         524         574         624

答案 2 :(得分:0)

我不知道单个UPDATE声明是否会这样做。我为每个Variable指定了值,如下面的

SELECT @SunTotal =  [sum]
                    FROM [table] 
                    where rdate = @Startdate

SELECT @MonTotal =  [sum]
                    FROM [table] 
                    where rdate = DATEADD(DAY,1,@Startdate)

SO ON...