基于整数字段计算新列

时间:2015-01-15 21:55:01

标签: sql sqlite

我有一个包含整数列的表,名为“Day1Reg”,“Day2Reg”,......“Day7Reg”,“Day1OT”,“Day2OT”,......“Day7OT”。我想选择表中的所有行,计算2个名为“WkReg”和“WkOT”的新列,它们将是DayxReg和DayxOT的总和。 Dayx列可能为null。这是迄今为止的查询:

select
  *,
  (Day1Reg+Day2Reg+Day3Reg+Day4Reg+Day5Reg+Day6Reg+Day7Reg) as WkReg,
  (Day1OT+Day2OT+Day3OT+Day4OT+Day5OT+Day6OT+Day7OT) as WkOT
from
  Week01
where
  UserName = "JustMe"

创建了WkReg和WkOT列,但没有值。在几个Dayx列中有整数值。不返回任何错误,只返回WkReg和WkOT中的空白值。

2 个答案:

答案 0 :(得分:2)

据推测,某些整数值为NULL,这导致整个总和为NULL。您可以使用coalesce()将值替换为0

select w.*
       (coalesce(Day1Reg, 0) + coalesce(Day2Reg, 0) + coalesce(Day3Reg, 0) +
        coalesce(Day4Reg, 0) + coalesce(Day5Reg, 0) + coalesce(Day6Reg, 0) + coalesce(Day7Reg, 0)
       ) as WkReg,
       (coalesce(Day1OT, 0) + coalesce(Day2OT, 0) + coalesce(Day3OT, 0) +
        coalesce(Day4OT, 0) + coalesce(Day5OT, 0) + coalesce(Day6OT, 0) + coalesce(Day7OT, 0)
       ) as WkOT
from Week01 w
where w.UserName = 'JustMe';

答案 1 :(得分:0)

UPDATE `Week01` SET `WkReg` = (Day1Reg+Day2Reg+Day3Reg+Day4Reg+Day5Reg+Day6Reg+Day7Reg), 
`WkOT`=(Day1OT+Day2OT+Day3OT+Day4OT+Day5OT+Day6OT+Day7OT) 
WHERE `UserName` = "JustMe"