选择按月份分组的两个日期之间的用户计数,并在count = 0

时间:2017-08-16 12:58:16

标签: mysql sql database

选择按月份分组的两个日期之间的用户计数,并在count = 0的月份中包括零。

当前查询:

select count(u_id) as users, monthname(register_date) as month_name,year(register_date) as year
from user
where register_date >= '2017-01-01' and register_date <= '2018-01-31'
group by year(register_date), month(register_date); 

返回结果:

users, month_name, year
'1',   'August',  '2017'

预期产出:

users, month_name, year
0      'Jan'       '2017'
0      'Feb'       '2017'
0      'March'       '2017'
0      'April'       '2017'
0      'May'       '2017' 
0      'June'       '2017'
0      'July'       '2017'
1      'Aug'       '2017'
0      'Sept'       '2017'
0      'Oct'       '2017'
0      'Nov'       '2017'
0      'Dec'       '2017'
0      'Jan'       '2018'

我搜索了许多链接,但它不符合我对项目的要求。请帮忙。 提前完成。

3 个答案:

答案 0 :(得分:0)

创建一个包含所有日期的表格,然后Thread.Sleep(2000); //time is in milliseconds 创建已有的日期。

left join

Dates created like here

答案 1 :(得分:0)

请尝试此查询:

DECLARE @FromDate DATETIME, @ToDate DATETIME;
SET @FromDate = '2013-01-01';
SET @ToDate = '2014-12-31';


SELECT TOP (DATEDIFF(MONTH, @FromDate, @ToDate)+1)
 MONTH(DATEADD(MONTH, number, @FromDate)) TheMonth,
  YEAR(DATEADD(MONTH, number, @FromDate)) TheYear
  INTO Data
  FROM [master].dbo.spt_values 
  WHERE [type] = N'P' ORDER BY number;

select * from Data 

select  Data.TheMonth,Data.TheYear,  Isnull(tmp.users,0) as usercount
from    Data 
        LEFT OUTER JOIN (select count(1) as users, month(register_date) as month_name,year(register_date) as year 
                        from    user 
                        where   CONVERT(nvarchar(121), register_date , 121) >=CONVERT(nvarchar(121),@FromDate  , 121) 
                                AND CONVERT(nvarchar(121), register_date , 121) <=CONVERT(nvarchar(121), @ToDate  , 121) 
                         group by year(register_date), month(register_date) ) tmp on tmp.month_name = Data.TheMonth AND tmp.year = Data.TheYear

DROP TABLE Data

答案 2 :(得分:0)

请创建一个包含所有日期的临时表(#temp_tbl),然后以下查询应生成您期望的结果:

select  count(u_id) as users, 
        monthname(register_date) as month_name,
        year(register_date) as year 
    from [user]
    where register_date >='2017-01-01' and register_date<='2018-01-31'
    group by year(register_date),month(register_date)
union
 select '0' as users, 
         monthname(register_date) as month_name,
         year(register_date) as year 
    from #temp_tbl 
    where  register_date >= '2017-01-01' and register_date<='2018-01-31'

此致 阿卜杜拉