1

我想在我的选择语句中添加新列

SELECT name,line,style,operation,
7to8am,8to9am,9to10am,10to11am,11to12am,
1to2pm,2to3pm,3to4pm,4to5pm,5to6pm,6to7pm,7to8pm,8to9pm,9to10pm,10to11pm,11to12pm,
sum(7to8am+8to9am+9to10am+10to11am+11to12am+1to2pm
+2to3pm+3to4pm+4to5pm+5to6pm+6to7pm+7to8pm+
8to9pm+9to10pm+10to11pm+11to12pm) as DailyTotal,id from new_hourly GROUP By line

我想添加一个新列,显示今天的 DailyTotal 总和

这是我的 sql 备份文件 http://www.uploadmb.com/dw.php?id=1446536983

请帮我!太感谢了!

4

1 回答 1

1

所以你想要一个额外的列,只添加datee等于当前日期的行?

在这种情况下,我会选择 case-when 表达式:

coalesce(
      sum(
        case 
          when datee = CURDATE() 
             then 7to8am+8to9am+9to10am+10to11am+11to12am+1to2pm+2to3pm+3to4pm+4to5pm+5to6pm+6to7pm+7to8pm+8to9pm+9to10pm+10to11pm+11to12pm 
             else null 
          end
         )
    ,0) as TodaysTotal

这只是总结了 column 所在的行,datee如果curdate()今天根本没有行,则返回 0。

完整的 SQL:

SELECT name,line,style,operation,
7to8am,8to9am,9to10am,10to11am,11to12am,
1to2pm,2to3pm,3to4pm,4to5pm,5to6pm,6to7pm,7to8pm,8to9pm,9to10pm,10to11pm,11to12pm,
sum(7to8am+8to9am+9to10am+10to11am+11to12am+1to2pm
+2to3pm+3to4pm+4to5pm+5to6pm+6to7pm+7to8pm+
8to9pm+9to10pm+10to11pm+11to12pm) as DailyTotal,

coalesce(
  sum(
    case 
      when datee = CURDATE() 
         then 7to8am+8to9am+9to10am+10to11am+11to12am+1to2pm+2to3pm+3to4pm+4to5pm+5to6pm+6to7pm+7to8pm+8to9pm+9to10pm+10to11pm+11to12pm 
         else null 
      end
     )
,0) as TodaysTotal

,id from new_hourly GROUP By line
于 2015-11-03T08:12:15.757 回答