select number from master..spt_values where type='p' 三,如何产生连续的时间段(年, 月, 天,小时,分钟)
在实际的运用中,目前主要是产生连续的时间段。我准备了常用的操作,那下面的语句就分别展示出来。
-- 按年产生连续的
SELECT
substring(CONVERT(NVARCHAR(10), DateAdd(YEAR, number, '2016-01-01'),120),1,4) AS GroupDay,type
FROM
master..spt_values
WHERE type = 'p' AND number <= DateDiff(YEAR, '2016-01-01', '2019-01-01')
-- 按月产生连续的
SELECT
substring(CONVERT(NVARCHAR(10), DateAdd(MONTH, number, '2019-01-01'),120),1,7) AS GroupDay,type
FROM
master..spt_values
WHERE type = 'p' AND number <= DateDiff(MONTH, '2018-01-01', '2019-01-01')
-- 按天产生连续的
SELECT
CONVERT(NVARCHAR(10), DateAdd(day, number, '2019-01-01'),120) AS GroupDay,type
FROM
master..spt_values
WHERE type = 'p' AND number <= DateDiff(day, '2019-01-01', '2019-01-18')
-- 按小时产生连续的
SELECT
substring(convert(char(32),DATEADD(HH,number,CONCAT('2019-01-18',' ', '00:00')),120),1,16) AS GroupDay,type
FROM
master..spt_values
WHERE type = 'p' AND DATEDIFF(HH,DATEADD(HH,number,CONCAT('2019-01-18',' ', '00:00')),CONCAT('2019-01-18',' ', '23:00'))>=0
-- 按分钟的就自己可以YY了
......
-- 按天统计交易笔数
select a.GroupDay, ISNULL(b.e, 0) 'feeCount' from (
SELECT
CONVERT(NVARCHAR(10), DateAdd(day, number, @paySdate),120) AS GroupDay,type
FROM
master..spt_values
WHERE
type = 'p' AND number <= DateDiff(day, @paySdate, @payEdate)
) a
left join
(select
convert(char(32),create_time,23) as d, count(*) as e
from
trade_log where create_time >= @paySdate and create_time<=@payEdate
group by convert(char(32),create_time,23)) b on b.d=a.GroupDay
-- 按小时统计交易笔数
select a.GroupDay, ISNULL(b.e,0) 'feeCount' from (
SELECT
substring(convert(char(32),DATEADD(HH,number,CONCAT(@paySdate,' ', @paySTime)),120),1,16) AS GroupDay,type
FROM
master..spt_values
WHERE
type = 'p' AND DATEDIFF(HH,DATEADD(HH,number,CONCAT(@paySdate,' ', @paySTime)),CONCAT(@payEdate,' ', @payETime))>=0
) a
left join (
select
convert(char(32),create_time,23) as d, datepart(hh,create_time) as h,
substring(convert(char(32),DATEADD(HH,datepart(hh,create_time),convert(char(32),create_time,23)),120),1,16) as st,
count(*) as e
from
trade_log
where create_time >= @paySdate and create_time<=@payEdate
and convert(char(8),create_time,108)>=@paySTime and convert(char(8),create_time,108)<=@payETime
group by convert(char(32),create_time,23),datepart(hh,create_time)) b
on b.st=a.GroupDay order by GroupDay
select DATE_FORMAT(create_time,'%Y%m%d') days,count(caseid) count from tc_case group by days;
select DATE_FORMAT(create_time,'%Y%u') weeks,count(caseid) count from tc_case group by weeks;
select DATE_FORMAT(create_time,'%Y%m') months,count(caseid) count from tc_case group by months;