结果是生成null而减去两个变量

时间:2018-03-29 05:47:04

标签: mysql datetime variables null subtraction

SELECT DAYOFWEEK('2018/08/15');
SET @STARTDATE = '2017/08/15';
SET @ENDDATE = '2018/08/15';

  #1->part1


 SET @SEC_IN_START_DATE = UNIX_TIMESTAMP(@STARTDATE);
 SET @SEC_IN_END_DATE = UNIX_TIMESTAMP(@ENDDATE);
 SELECT @NUM_OF_DAYS = (@SEC_IN_END_DATE - @SEC_IN_START_DATE);
 SELECT @NUM_OF_WEEKS = (@NUM_OF_DAYS%7);  
 SELECT UNIX_TIMESTAMP(@ENDDATE);  
 #part-2
 SELECT 
     ROUND((
          (unix_timestamp(@END_DATE) - unix_timestamp(@START_DATE) ) 
          /(24*60*60)
              -7+WEEKDAY(@START_DATE)-WEEKDAY(@END_DATE)
          )/7);

执行时上面显示的所有部分都给出了值the image shows execution of part 2& the image shows execution of part 1 但两者都给出了空,请帮助。 谢谢你的帮助。

3 个答案:

答案 0 :(得分:0)

如果您将它们转换为日期时间数据类型,可能是您正在对字符串类型数据类型进行操作

答案 1 :(得分:0)

您的变量声明与使用情况不同,请更新您的查询,如下所示。

SELECT 
     ROUND((
          (unix_timestamp(@ENDDATE) - unix_timestamp(@STARTDATE) ) 
          /(24*60*60)
              -7+WEEKDAY(@STARTDATE)-WEEKDAY(@ENDDATE)
          )/7);

O / P:

 SELECT       ROUND((           (unix_timestamp(@ENDDATE) - unix_timestamp(@STARTDATE) )            /(24*60*60)               -7+WEEKDAY(@STARTDATE)-WEEKDAY(@ENDDATE)           )/7); +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ROUND((           (unix_timestamp(@ENDDATE) - unix_timestamp(@STARTDATE) )            /(24*60*60)               -7+WEEKDAY(@STARTDATE)-WEEKDAY(@ENDDATE)           )/7) |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|                                                                                                                                                                      51 |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

答案 2 :(得分:0)

您的查询存在一些问题。首先,在SELECT语句中,必须使用:=来完成变量分配,而不是=,因为=用于比较。其次,在第2部分查询中,您使用了@START_DATE@END_DATE而不是@STARTDATE@ENDDATE。第三,要计算NUM_OF_WEEKS,您应该使用NUM_OF_DAYS / 7(或NUM_OF_DAYS DIV 7进行整数运算),而不是NUM_OF_DAYS % 7

尝试将您的查询更改为:

SET @STARTDATE = '2017/08/15';
SET @ENDDATE = '2018/08/15';
SELECT @SEC_IN_START_DATE := UNIX_TIMESTAMP(@STARTDATE);
SELECT @SEC_IN_END_DATE := UNIX_TIMESTAMP(@ENDDATE);
SELECT @NUM_OF_DAYS := @SEC_IN_END_DATE - @SEC_IN_START_DATE;
SELECT @NUM_OF_WEEKS := @NUM_OF_DAYS / 7;
SELECT 
  ROUND((
     (UNIX_TIMESTAMP(@ENDDATE) - UNIX_TIMESTAMP(@STARTDATE) ) 
     /(24*60*60)
     -7+WEEKDAY(@STARTDATE)-WEEKDAY(@ENDDATE)
     )/7);