我有一个表格如下
| ID | CREATED | TITLE |
| 1 | 07/09/2015 14:02:48 | Render farm problem |
| 2 | 06/16/2015 09:34:20 | Render server THSSE12 crashing |
| 3 | 05/16/2015 09:44:38 | Patch to LG4 switch port 25 |
我希望能够计算TITLE字段中关键字的出现次数,例如按年和月来渲染和格式化结果
| YEAR | MONTH | COUNT |
|2015 | 5 | 0 |
|2015 | 6 | 1 |
|2015 | 7 | 1 |
我已经尝试了几个内连接,但没有任何喜悦,因为0计数的月份没有显示。这就是我所在的地方: -
SELECT
CONCAT(YEAR(c.CREATED),MONTH(c.CREATED)) AS cdate,
c.CREATED,
COUNT(c.ID)
FROM
HD_TICKET AS c
LEFT JOIN
(SELECT
CONCAT(YEAR(t.CREATED),MONTH(t.CREATED)) AS sdate,
t.CREATED,
COUNT(t.ID) AS tid
FROM HD_TICKET t
WHERE t.TITLE LIKE '%render%'
) AS t_count
ON c.CREATED = t_count.CREATED
GROUP BY YEAR(c.CREATED), MONTH(c.CREATED)
我真的很感激任何帮助!
答案 0 :(得分:0)
未经测试,但我相信这会为您提供所需。使用带有SUM()
表达式的CASE
来计算子字符串的出现次数。
它使用一个小技巧来检查列的长度,将子字符串的出现替换为0个字符,并从原始字符串中减去新字符串的长度,然后将结果四舍五入除以您的长度。 substring:)
<强>区分大小写:强>
select
year(created) as year,
month(created) as month,
SUM(CASE WHEN title like '%render%' THEN round((length(title)-length(replace(title, 'render', '')))/length('render')) ELSE 0 END) AS count
from
hd_ticket
group by
year(created), month(created)
不区分大小写lower()
:
select
year(created) as year,
month(created) as month,
SUM(CASE WHEN lower(title) like lower('%reNder%') THEN round((length(title)-length(replace(lower(title), lower('reNder'), '')))/length('reNder')) ELSE 0 END) AS count
from
hd_ticket
group by
year(created), month(created);
不区分大小写的搜索将为您提供预期的输出。
| year | month | count |
+------+-------+-------+
|2015 | 5 | 0 |
|2015 | 6 | 1 |
|2015 | 7 | 1 |
答案 1 :(得分:0)
首先生成所有年/月值,然后左键加入所需数据。所有细节内联。如果你愿意,你可以使用相同的技巧多年。 fiddle here
select calendar.year_, calendar.month_,
coalesce(mydata.count_,0) as count_ -- coalesce used to obtain 0 on missing data.
from
( select y.year_, m.month_
from
(select distinct YEAR(CREATED) as year_ FROM hd_ticket) as y -- all posible years
, -- comma here produces cross join
(select 1 as month_ union all select 2 -- all months
union all select 3 union all select 4
union all select 5 union all select 6
union all select 7 union all select 8
union all select 9 union all select 10
union all select 11 union all select 12) as m
) as calendar -- a calendar: all years and all months
left join
(
select count(*) as count_, year(CREATED) as year_, month(CREATED) as month_
from HD_TICKET
where TITLE like '%render%'
group by year(CREATED), month(CREATED)
) as mydata
on calendar.year_ = mydata.year_ and calendar.month_ = mydata.month_
order by 1, 2