我在查询时遇到麻烦。我需要在分组行中获取计数。 最终结果应该像这样
id title record_date record_timerange count
109 game 2018-07-09 12:00-13:00 1
106 game 2018-07-09 11:00-12:00 3
116 book 2018-07-09 08:00-09:00 3
104 game 2018-07-09 08:00-09:00 2
115 game 2018-07-08 12:00-13:00 1
112 game 2018-07-08 11:00-12:00 3
110 game 2018-07-08 08:00-09:00 2
这是我的SQL和小提琴http://sqlfiddle.com/#!9/9d27d9/1
Select id, title,
DATE_FORMAT(record_datetime, '%Y-%m-%d')as record_date,
Concat(DATE_FORMAT(record_datetime, '%H'),':00-', LPAD( DATE_FORMAT(record_datetime, '%H')+01,2,0 ) ,':00')as record_timerange,
(select count(id) from nav_static_data as sub where 1=1
and sub.title=title
and DATE_FORMAT(sub.record_datetime,'%H')=record_date
and DATE_FORMAT(sub.record_datetime, '%Y-%m-%d')=DATE_FORMAT(record_datetime, '%Y-%m-%d')
)as count
from nav_static_data as m where 1=1
group by FLOOR(MOD(m.record_datetime, 86400)/8640), m.title
order by record_date desc, record_timerange desc, m.title
如何修复计数列和缺失的行(id = 110)?
答案 0 :(得分:2)
请尝试以下查询。
select title,
DATE_FORMAT(record_datetime, '%Y-%m-%d')as record_date,
Concat(DATE_FORMAT(record_datetime, '%H'),':00-', LPAD( DATE_FORMAT(record_datetime, '%H')+01,2,0 ) ,':00')as record_timerange,
count(title)
from nav_static_data
group by title, record_date,record_timerange
order by id
您只需使用group by即可获得结果,并且您确实需要使用子查询对结果进行计数。
答案 1 :(得分:0)
尝试一下
Select id, title, DATE_FORMAT(record_datetime, '%Y-%m-%d')as record_date,
Concat(DATE_FORMAT(record_datetime, '%H'),':00-', LPAD( DATE_FORMAT(record_datetime, '%H')+01,2,0 ) ,':00')as record_timerange,
(select count(id) from nav_static_data as sub
where sub.title=m.title
and DATE_FORMAT(sub.record_datetime, '%H')= DATE_FORMAT(m.record_datetime, '%H')
and DATE_FORMAT(sub.record_datetime, '%Y-%m-%d')=DATE_FORMAT(m.record_datetime, '%Y-%m-%d')
)as count
from nav_static_data as m
group by FLOOR(mod(m.record_datetime, 86400)/1440), m.title
order by record_date desc, record_timerange desc, m.title