背景:年底了,需要做一个分段统计报表,需要统计每个时间段(一个季度)创建了多少了个站点(site)。以下sql作为范本,并进行解析:
1. 时间分段:between 是左右闭合空间,所以注意时间点选择,以防止漏掉统计数据。
Q1: ['2017-01-01','2017-04-01']; Q2: ['2017-04-01','2017-07-01']...
2. Case when then分段统计数据;
3. 字符型转换成日期型:TO_DATE ('2017-07-01', 'yyyy-mm-dd')
4. 要利用group by (case when ... then ... end) 统计数据
5. "CreateDate" 这类别名,区分大小写,需要加双引号。
SELECT (CASE
WHEN CREATETIME < TO_DATE ('2017-01-01', 'yyyy-mm-dd')
THEN
'2016'
WHEN CREATETIME BETWEEN TO_DATE ('2017-01-01', 'yyyy-mm-dd')
AND TO_DATE ('2017-04-01', 'yyyy-mm-dd')
THEN
'2017Q1'
WHEN CREATETIME BETWEEN TO_DATE ('2017-04-01', 'yyyy-mm-dd')
AND TO_DATE ('2017-07-01', 'yyyy-mm-dd')
THEN
'2017Q2'
WHEN CREATETIME BETWEEN TO_DATE ('2017-07-01', 'yyyy-mm-dd')
AND TO_DATE ('2017-10-01', 'yyyy-mm-dd')
THEN
'2017Q3'
WHEN CREATETIME BETWEEN TO_DATE ('2017-10-01', 'yyyy-mm-dd')
AND TO_DATE ('2018-01-01', 'yyyy-mm-dd')
THEN
'2017Q4'
WHEN CREATETIME BETWEEN TO_DATE ('2018-01-01', 'yyyy-mm-dd')
AND TO_DATE ('2018-04-01', 'yyyy-mm-dd')
THEN
'2018Q1'
END)
AS "CreateDate",
COUNT (1) AS "SiteNumber"
FROM TableName
GROUP BY (CASE
WHEN CREATETIME < TO_DATE ('2017-01-01', 'yyyy-mm-dd')
THEN
'2016'
WHEN CREATETIME BETWEEN TO_DATE ('2017-01-01', 'yyyy-mm-dd')
AND TO_DATE ('2017-04-01', 'yyyy-mm-dd')
THEN
'2017Q1'
WHEN CREATETIME BETWEEN TO_DATE ('2017-04-01', 'yyyy-mm-dd')
AND TO_DATE ('2017-07-01', 'yyyy-mm-dd')
THEN
'2017Q2'
WHEN CREATETIME BETWEEN TO_DATE ('2017-07-01', 'yyyy-mm-dd')
AND TO_DATE ('2017-10-01', 'yyyy-mm-dd')
THEN
'2017Q3'
WHEN CREATETIME BETWEEN TO_DATE ('2017-10-01', 'yyyy-mm-dd')
AND TO_DATE ('2018-01-01', 'yyyy-mm-dd')
THEN
'2017Q4'
WHEN CREATETIME BETWEEN TO_DATE ('2018-01-01', 'yyyy-mm-dd')
AND TO_DATE ('2018-04-01', 'yyyy-mm-dd')
THEN
'2018Q1'
END)
ORDER BY (CASE
WHEN CREATETIME < TO_DATE ('2017-01-01', 'yyyy-mm-dd')
THEN
'2016'
WHEN CREATETIME BETWEEN TO_DATE ('2017-01-01', 'yyyy-mm-dd')
AND TO_DATE ('2017-04-01', 'yyyy-mm-dd')
THEN
'2017Q1'
WHEN CREATETIME BETWEEN TO_DATE ('2017-04-01', 'yyyy-mm-dd')
AND TO_DATE ('2017-07-01', 'yyyy-mm-dd')
THEN
'2017Q2'
WHEN CREATETIME BETWEEN TO_DATE ('2017-07-01', 'yyyy-mm-dd')
AND TO_DATE ('2017-10-01', 'yyyy-mm-dd')
THEN
'2017Q3'
WHEN CREATETIME BETWEEN TO_DATE ('2017-10-01', 'yyyy-mm-dd')
AND TO_DATE ('2018-01-01', 'yyyy-mm-dd')
THEN
'2017Q4'
WHEN CREATETIME BETWEEN TO_DATE ('2018-01-01', 'yyyy-mm-dd')
AND TO_DATE ('2018-04-01', 'yyyy-mm-dd')
THEN
'2018Q1'
END);