這裏的細節根據您的樣本數據:
詳細結果:
select MonthAdded,count(date_substr) as cnt from
(select '2017-01'as MonthAdded UNION all
select '2017-02' UNION all
select '2017-03' UNION all
select '2017-04' UNION all
select '2017-05' UNION all
select '2017-06' UNION all
select '2017-07' UNION all
select '2017-08' UNION all
select '2017-09' UNION all
select '2017-10' UNION all
select '2017-11' UNION all
select '2017-12') as a
left join
(select id, user_id, action, date_added,SUBSTRING(date_added FROM 1 FOR 7) as date_substr from
(select 75 as id, 56 as user_id, 'Base Adding' action, '2017-02-29 11:52:35' as date_added UNION all
select 76, 56, 'Base Adding', '2017-02-29 11:59:28' UNION all
select 77, 61, 'Fuel Adding', '2017-02-29 12:05:16' UNION all
select 78, 56, 'Update details' , '2017-02-29 12:17:08' UNION all
select 79, 57, 'Logged In' , '2017-02-29 12:25:41' UNION all
select 80, 56, 'Base Adding', '2017-03-29 12:40:56' UNION all
select 81, 55, 'Logged In' , '2017-02-29 12:51:31' UNION all
select 82, 56, 'Base Adding', '2017-05-29 12:53:25') as a
where action = 'Base Adding' and user_id = 56) as b
on a.MonthAdded = b.date_substr
group by MonthAdded
最終查詢結構:
select MonthAdded,count(date_substr) as cnt from
(select '2017-01'as MonthAdded UNION all
select '2017-02' UNION all
select '2017-03' UNION all
select '2017-04' UNION all
select '2017-05' UNION all
select '2017-06' UNION all
select '2017-07' UNION all
select '2017-08' UNION all
select '2017-09' UNION all
select '2017-10' UNION all
select '2017-11' UNION all
select '2017-12') as a
left join
(select id, user_id, action, date_added,SUBSTRING(date_added FROM 1 FOR 7) as date_substr from
(select * from yourtable) as a
where action = 'Base Adding' and user_id = 56) as b
on a.MonthAdded = b.date_substr
group by MonthAdded
它包括直到十二月,如果你確保有一個關於它的數據。
結果:
2017-01 0
2017-02 2
2017-03 1
2017-04 0
2017-05 1
2017-06 0
2017-07 0
2017-08 0
2017-09 0
2017-10 0
2017-11 0
2017-12 0
這是不可能的..你有這樣的2017-02超過2個字。 –
針對基本添加的操作對於2017年爲2 – Rhynix
明確提出問題... –