因為做一些商場某個會員今年的消費分析,所以對sql中時間的獲取進行了判斷。
例如獲取今年(即當前年的第一天到昨天0時之間)的消費總額。
如果需要時間戳轉換,用UNIX_TIMESTAMP()函式。
一 、下面是一些mysql的時間獲取語句:
#當年第一天: SELECT DATE_SUB(CURDATE(),INTERVAL dayofyear(now())-1 DAY); #當年最後一天: SELECT concat(YEAR(now()),`-12-31`); #當前week的第一天: select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) + 1 DAY); #當前week的最後一天: select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) - 5 DAY); #前一week的第一天: select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) + 8 DAY); #前一week的最後一天: select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) + 2 DAY); #前兩week的第一天: select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) + 15 DAY); #前兩week的最後一天: select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) + 9 DAY); #當前month的第一天: SELECT concat(date_format(LAST_DAY(now()),`%Y-%m-`),`01`); #當前month的最後一天: SELECT LAST_DAY(now()); #前一month的第一天: SELECT concat(date_format(LAST_DAY(now() - interval 1 month),`%Y-%m-`),`01`); #前一month的最後一天: SELECT LAST_DAY(now() - interval 1 month); #前兩month的第一天: SELECT concat(date_format(LAST_DAY(now() - interval 2 month),`%Y-%m-`),`01`); #前兩month的最後一天: SELECT LAST_DAY(now() - interval 2 month); #當前quarter的第一天: select concat(date_format(LAST_DAY(MAKEDATE(EXTRACT(YEAR FROM CURDATE()),1) + interval QUARTER(CURDATE())*3-3 month),`%Y-%m-`),`01`); #當前quarter的最後一天: select LAST_DAY(MAKEDATE(EXTRACT(YEAR FROM CURDATE()),1) + interval QUARTER(CURDATE())*3-1 month); #前一quarter的第一天: select concat(date_format(LAST_DAY(MAKEDATE(EXTRACT(YEAR FROM CURDATE()),1) + interval QUARTER(CURDATE())*3-6 month),`%Y-%m-`),`01`); #前一quarter的最後一天: select LAST_DAY(MAKEDATE(EXTRACT(YEAR FROM CURDATE()),1) + interval QUARTER(CURDATE())*3-4 month); #前兩quarter的第一天: select concat(date_format(LAST_DAY(MAKEDATE(EXTRACT(YEAR FROM CURDATE()),1) + interval QUARTER(CURDATE())*3-9 month),`%Y-%m-`),`01`); #前兩quarter的最後一天: select LAST_DAY(MAKEDATE(EXTRACT(YEAR FROM CURDATE()),1) + interval QUARTER(CURDATE())*3-7 month);
二、舉幾個某會員的消費分析的sql語句:
-- 今年的消費總額 SELECT IFNULL(SUM(a.trade_amount)/100,0) FROM mob_checkout_counter.checkout_record a -- 消費記錄表 WHERE card_code = `某會員的標識` AND checkout_status = ‘消費狀態’AND trade_time >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(),INTERVAL dayofyear(now())-1 DAY)) -- 當前年的第一天的時間戳 AND trade_time <= UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE) - INTERVAL 1 DAY) -- 昨天的0時的時間戳 -- 今年的消費筆數 SELECT COUNT(*) FROM mob_checkout_counter.checkout_record a WHERE card_code = `2396998881100009965` AND checkout_status = 1 AND trade_time >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(),INTERVAL dayofyear(now())-1 DAY)) AND trade_time <= UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE) - INTERVAL 1 DAY) -- 今年的客單價 SELECT IFNULL(SUM(a.trade_amount)/100,0)/COUNT(*) FROM mob_checkout_counter.checkout_record a WHERE card_code = `2396998881100009965` AND checkout_status = 1 AND trade_time >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(),INTERVAL dayofyear(now())-1 DAY)) AND trade_time <= UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE) - INTERVAL 1 DAY)