1. 程式人生 > >關於月 季 周 日的統計完善

關於月 季 周 日的統計完善

之前寫的那個只能獲取固定的某年,某季,某月,某天的統計,這讓我做報表的很難受,於是上網百度加自己理解寫了如下的方法

凡是結果同月的第二個方法便於一個報表統計,方法只需寫一個,謹慎選擇

月:

1.

SELECT
SUM( CASE MONTH ( a.createTime ) WHEN '1' THEN 1 ELSE 0 END ) AS january,
SUM( CASE MONTH ( a.createTime ) WHEN '2' THEN 1 ELSE 0 END ) AS february,
SUM( CASE MONTH ( a.createTime ) WHEN '3' THEN 1 ELSE 0 END ) AS march,
SUM( CASE MONTH ( a.createTime ) WHEN '4' THEN 1 ELSE 0 END ) AS april,
SUM( CASE MONTH ( a.createTime ) WHEN '5' THEN 1 ELSE 0 END ) AS may,
SUM( CASE MONTH ( a.createTime ) WHEN '6' THEN 1 ELSE 0 END ) AS june,
SUM( CASE MONTH ( a.createTime ) WHEN '7' THEN 1 ELSE 0 END ) AS july,
SUM( CASE MONTH ( a.createTime ) WHEN '8' THEN 1 ELSE 0 END ) AS august,
SUM( CASE MONTH ( a.createTime ) WHEN '9' THEN 1 ELSE 0 END ) AS september,
SUM( CASE MONTH ( a.createTime ) WHEN '10' THEN 1 ELSE 0 END ) AS october,
SUM( CASE MONTH ( a.createTime ) WHEN '11' THEN 1 ELSE 0 END ) AS november,
SUM( CASE MONTH ( a.createTime ) WHEN '12' THEN 1 ELSE 0 END ) AS december
FROM
`gm_buyerproduct` a
WHERE
YEAR(createTime) = YEAR("2018-9-6")

如果你就要確定的12個月的統計,用這個很清楚,但報表的橫座標就是固定值了,不好做其他的方法統計

2.

SELECT COUNT(createTime) countStatus,
MONTH(createTime) AS monthflg
FROM
`gm_buyerproduct`
WHERE
YEAR(createTime)=YEAR("2018-12-6")
GROUP BY monthflg

這方法好處是橫座標是變數,但是隻能統計月份有數值,沒數值不會顯示,導致結構可能是:1月,2月,4月有值顯示,3月沒值就不顯示

季:

1.

SELECT
SUM( CASE QUARTER ( a.createTime ) WHEN '1' THEN 1 ELSE 0 END ) AS aa,
SUM( CASE QUARTER ( a.createTime ) WHEN '2' THEN 1 ELSE 0 END ) AS ss,
SUM( CASE QUARTER ( a.createTime ) WHEN '3' THEN 1 ELSE 0 END ) AS dd,
SUM( CASE QUARTER ( a.createTime ) WHEN '4' THEN 1 ELSE 0 END ) AS ff

FROM
`gm_buyerproduct` a
WHERE
YEAR(createTime) = YEAR("2018-9-6")

效果如月1

2.

SELECT COUNT(createTime) createTime,
QUARTER(createTime) modifiedTime
FROM
`gm_buyerproduct`
WHERE
YEAR(createTime) = YEAR("2018-8-8")
GROUP BY modifiedTime

同月2

 

周:

SELECT COUNT(createTime) countStatus,
WEEK(createTime) weeks
FROM
`gm_buyerproduct`
WHERE
MONTH(createTime)=MONTH("2018-12-19")AND YEAR(createTime)=YEAR("2018-12-16")
GROUP BY weeks

結果同月2,我這是統計一個月的周,統計某年所有周將MONTH(createTime)=MONTH("2018-12-19")AND 去了就行

天:

SELECT DATE_FORMAT (createTime,"%m-%d") createTimes,COUNT(createTime) countStatus ,YEAR(createTime) years
FROM `gm_buyerproduct`
WHERE WEEK(createTime)=WEEK("2018-12-16") AND YEAR(createTime)=YEAR("2018-12-16")
GROUP BY createTimes

結果同月2這是統計某周的7天,根據需求來加減條件