如何将总列添加到表中?

时间:2014-09-18 18:59:13

标签: sql sql-server tsql

我有以下查询:

SELECT * FROM [DSPCONTENT01].[dbo].[zWMGWEEKARRIVAL]
WHERE
[ARRIVED DATE] = 'WEEKLY TOTAL' OR [ARRIVED DATE] = 'PRIOR WEEK' OR [ARRIVED DATE] = '12 WEEK AVERAGE'

显示:

enter image description here

有没有办法添加另一个列或从中创建另一个表,在那里添加总数?

示例:

ARRIVED DATE     TOTAL

WEEKLY TOTAL     12000
PRIOR WEEK       13654
12 WEEK AVERAGE  10094

2 个答案:

答案 0 :(得分:1)

只需使用+,但请注意NULL s:

SELECT [ARRIVED DATE],
       (coalesce(col1, 0) + coalesce(col2, 0) + coalesce(col3, 0), . . .
       ) as Total
FROM [DSPCONTENT01].[dbo].[zWMGWEEKARRIVAL]
WHERE [ARRIVED DATE] IN ('WEEKLY TOTAL', 'PRIOR WEEK', '12 WEEK AVERAGE');

我无法轻易阅读您的列名,但您应该包含真实姓名。

答案 1 :(得分:1)

如果您希望将和作为数据库中的列,则可以添加所谓的computed column。您基本上只需添加一个查询作为列。您可以在计算列规范下的表设计器中的SSMS内执行此操作,也可以通过链接中所述的alter table语句执行此操作。

ALTER TABLE zWMGWEEKARRIVAL 
ADD Total AS (Theall + TheallUC + ....rest of columns )