我在MariaDB中有一个名为“事件”的表,下面是数据
<connectionStrings><add name="MyEntities" connectionString="metadata=res://*/Model.MyReplicationModel.csdl|res://*/Model.MyReplicationModel.ssdl|res://*/Model.MyReplicationModel.msl;provider=System.Data.SqlClient;provider connection string="data source=********;initial catalog=**********;persist security info=True;user id=sa;password=*******;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"/></connectionStrings>
我想计算一个月中每天每天的所有“开放”状态,并使用一个参数来选择要获取的月份和年份。
例如,我的月份值为“ 07”,年份为“ 2018”。它应该返回:
+-----+----------+---------------------+
| ID | status | created_at |
+-----+----------+---------------------+
| 1 | open | 2018-07-03 16:15:24 |
| 2 | open | 2018-07-03 16:15:24 |
| 3 | open | 2018-07-05 16:15:24 |
| 4 | open | 2018-07-08 16:15:24 |
| 5 | closed | 2018-07-15 16:15:24 |
+-----+----------+---------------------+
答案 0 :(得分:1)
请尝试以下查询:
select thedate,case when status is null then 0 else 1 end as count
from (Select '2018-07-01' As [TheDate]
Union All
Select DateAdd(month, 1, TheDate) From dt Where [TheDate] < '2018-07-31') as dt left join tablename
on dt.thedate=tablename.date
答案 1 :(得分:0)
使用下面的代码来实现结果集。
声明两个变量:
var_from_date =月的第一天的日期。 var_daydiff =每月的天数
WITH RECURSIVE cte_days (months, days, dates, n) AS
(
SELECT DATE(DATE_ADD(var_from_date, INTERVAL 0 DAY)) as dates,
0 as n
UNION ALL
SELECT DATE(DATE_ADD(var_from_date, INTERVAL n+1 DAY)) as dates,
n + 1 as n
FROM cte_days WHERE n <= var_daydiff
)
SELECT ch.date, IFNULL(COUNT(t.id), 0) as count
FROM cte_days ch
LEFT JOIN table t on ch.dates = t.date
GROUP BY ch.date;
答案 2 :(得分:0)
以下您可以根据需要生成日期的方式我已经给where gen_date between '2018-07-01' and '2018-12-31'
了,您必须使用放置并使用case when
和aggregate
函数的日期条件
select gen_date as date ,sum(case when status='open' then 1 else 0 end) as Cnt from
( select * from
(select adddate('1970-01-01',t4*10000 + t3*1000 + t2*100 + t1*10 + t0) gen_date from
(select 0 t0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 t1 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 t2 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 t3 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 t4 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where gen_date between '2018-07-01' and '2018-12-31'
) as T1 left join your_table t2 on T1.gen_date= date(t2.created_at)
group by gen_date