日期差的天时分秒表示SQL

 

文章出自:http://blog.csdn.net/wzy0623/article/details/7684513

 

#两日期/时间之间相差的天数: 
To_Days(end_time)-To_Days(start_time) 
  
#两日期/时间之间相差的秒数: 
SELECT UNIX_TIMESTAMP(end_time)- UNIX_TIMESTAMP(start_time); 
  
#两日期/时间之间相差的时分数: 
SELECT SEC_TO_TIME(UNIX_TIMESTAMP(end_time)- UNIX_TIMESTAMP(start_time));

 

 

MySQL实现方式:

SET @a:=UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(CURRENT_DATE());

-- 可以直接将set中变量a的值写入SQL语句中

SELECT CONCAT(IF(TRUNCATE(@a/24/3600,0)=0,'',CONCAT(TRUNCATE(@a/24/3600,0),'天')),
              IF(MOD(TRUNCATE(@a/3600,0),24)=0,'',CONCAT(MOD(TRUNCATE(@a/3600,0),24),'小时')),
              IF(MOD(TRUNCATE(@a/60,0),60)=0,'',CONCAT(MOD(TRUNCATE(@a/60,0),60),'分')),
              IF(MOD(@a,60)=0,'',CONCAT(MOD(@a,60),'秒'))) dt_diff;

 

oracle实现方式:

WITH a
             AS (SELECT   SYSDATE - TRUNC(SYSDATE) tt
                   FROM DUAL)
        SELECT    DECODE (TRUNC (tt, 0), 0, NULL, TRUNC (tt, 0) || '天')
               || DECODE (TRUNC (MOD (tt, 1) * 24, 0),
                          0, NULL,
                          TRUNC (MOD (tt, 1) * 24, 0) || '小时')
               || DECODE (TRUNC (MOD (tt * 24, 1) * 60, 0),
                          0, NULL,
                          TRUNC (MOD (tt * 24, 1) * 60, 0) || '分')
               || DECODE (ROUND (MOD (tt * 24 * 60, 1) * 60, 0),
                          0, NULL,
                          ROUND (MOD (tt * 24 * 60, 1) * 60, 0) || '秒')
                  dt_diff
          FROM a;

 

 

 

 

 

你可能感兴趣的:(oracle,mysql,time,time,sub,sub,日期差的天时分秒表示SQL)