mysql oracle统计报表每天每月每年SQL

mysql查询当天、昨天、本周、上周、近7天、近30天、本月、上个月、近6个月、本季度、上季度、本年和去年的数据

注意
在 XML 中
< 应该转为 <

当天
SELECT * FROM 表名 WHERE TO_DAYS(时间字段名) = TO_DAYS(NOW());

昨天
SELECT * FROM 表名 WHERE TO_DAYS(NOW()) - TO_DAYS(时间字段名) <= 1;

本周
SELECT * FROM 表名 WHERE YEARWEEK(DATE_FORMAT(时间字段名,'%Y-%m-%d')) = YEARWEEK(NOW());

上周
SELECT * FROM 表名 WHERE YEARWEEK(DATE_FORMAT(时间字段名,'%Y-%m-%d')) = YEARWEEK(NOW())-1;

近7天
SELECT * FROM 表名 WHERE DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= DATE(时间字段名);

近30天
SELECT * FROM 表名 WHERE DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= DATE(时间字段名);

本月
SELECT * FROM 表名 WHERE DATE_FORMAT(时间字段名,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m');

上个月
SELECT * FROM 表名 WHERE PERIOD_DIFF(DATE_FORMAT(NOW(),'%Y%m'),DATE_FORMAT(时间字段名,'%Y%m')) = 1;

SELECT * FROM 表名 WHERE DATE_FORMAT(时间字段名,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m') ; 

SELECT * FROM 表名 WHERE WEEKOFYEAR(FROM_UNIXTIME(时间字段名,'%y-%m-%d')) = WEEKOFYEAR(NOW()); 

SELECT * FROM 表名 WHERE MONTH(FROM_UNIXTIME(时间字段名,'%y-%m-%d')) = MONTH(NOW()); 

SELECT * FROM 表名 WHERE YEAR(FROM_UNIXTIME(时间字段名,'%y-%m-%d')) = YEAR(NOW()) AND MONTH(FROM_UNIXTIME(时间字段名,'%y-%m-%d')) = MONTH(NOW());

近6个月
SELECT * FROM 表名 WHERE 时间字段名 BETWEEN DATE_SUB(NOW(),INTERVAL 6 MONTH) AND NOW();

本季度
SELECT * FROM 表名 WHERE QUARTER(时间字段名) = QUARTER(NOW());

上季度
SELECT * FROM 表名 WHERE QUARTER(时间字段名) = QUARTER(DATE_SUB(NOW(),INTERVAL 1 QUARTER));

本年
SELECT * FROM 表名 WHERE YEAR(时间字段名)=YEAR(NOW());

去年
SELECT * FROM 表名 WHERE YEAR(时间字段名) = YEAR(DATE_SUB(NOW(),INTERVAL 1 YEAR));


Oracle几个常用的日期计算SQL示例

1、查询上月的所有日期:

SELECT TO_CHAR (TRUNC (TRUNC (SYSDATE, 'MM') - 1, 'month') + LEVEL - 1,
                        'yyyy-MM-dd')
                  AS month_day
          FROM DUAL
    CONNECT BY LEVEL <= TO_CHAR (LAST_DAY (TRUNC (SYSDATE, 'MM') - 1), 'dd');

2、查询当月的所有日期:

SELECT TO_CHAR (TRUNC (SYSDATE, 'month') + LEVEL - 1,
                        'yyyy-MM-dd')
                  AS month_day
          FROM DUAL
    CONNECT BY LEVEL <= TO_CHAR (LAST_DAY (TRUNC (SYSDATE, 'MM') - 1), 'dd');

3、查询上月月份:

SELECT TO_CHAR(ADD_MONTHS(SYSDATE,-1),'YYYY-MM') FROM DUAL; 

4、查询当月天数:

    SELECT TO_CHAR (LAST_DAY (TRUNC (SYSDATE, 'mm')), 'DD') mounth_count
      FROM DUAL;

5、查询当月第一天:

SELECT TRUNC (SYSDATE, 'month') FROM DUAL;

6、查询当月最后一天:

SELECT TO_CHAR (LAST_DAY (SYSDATE), 'YYYY-MM-DD') FROM DUAL;

7、计算两个日期之间天数:

SELECT   TO_DATE ('2013-08-05', 'yyyy-MM-dd')
           - TO_DATE ('2013-08-01', 'yyyy-MM-dd')
           + 1
              AS count_day
      FROM DUAL;

8、查询两个日期之间的所有日期:

 SELECT ROWNUM, TO_DATE ('2013-01-02', 'yyyy-MM-dd') + ROWNUM - 1 AS allday
          FROM DUAL
    CONNECT BY ROWNUM <
                    TO_DATE ('2013-01-07', 'yyyy-MM-dd')
                  - TO_DATE ('2013-01-02', 'yyyy-MM-dd')
                  + 2;

你可能感兴趣的:(sql,mysql,oracle,sql)