-2

I have a table where I want to retreive data every hourly from database in report format. like

username   8-9    9-10   10-11
====================================
kiran      20    27       33
Ram        25    23       44

Can we get like this in mysql please help.

select username,count(message) as '8-9' from customer_1.audit_trail
inner join inteliviz.users
on customer_1.audit_trail.user_id = inteliviz.users.id inner join 
customer_1.carparks on customer_1.carparks.id = customer_1.audit_trail.location_id 
where datetime>'2013-08-27 08:00:00' and datetime<'2013-08-27 09:00:00'
group by username  limit 1000;
4

2 回答 2

1

I think you are looking for conditional aggregation:

select username,
       sum(datetime >= '2013-08-27 08:00:00' and datetime < '2013-08-27 09:00:00') as "8-9",
       sum(datetime >= '2013-09-27 08:00:00' and datetime < '2013-08-27 10:00:00') as "9-10",
       sum(datetime >= '2013-08-27 10:00:00' and datetime < '2013-08-27 11:00:00') as "10-11"
from customer_1.audit_trail t inner join
     inteliviz.users u
     on t.user_id = 8.id inner join 
     customer_1.carparks cp
     on cp.id = t.location_id 
group by username 
limit 1000;

I also added table aliases to make the query easier to read. And, I changed the single quotes in column aliases to double quotes. It is a good idea to stick to using single quotes for strings and double quotes for aliases (which is consistent with the standard).

于 2013-08-27T12:28:44.420 回答
0

try using >= and <=

select username,count(message) as '8-9' from customer_1.audit_trail 
inner join inteliviz.users on customer_1.audit_trail.user_id = inteliviz.users.id 
inner join customer_1.carparks on customer_1.carparks.id = customer_1.audit_trail.location_id 
where datetime>='2013-08-27 08:00:00' and datetime<='2013-08-27 09:00:00'
group by username limit 1000;

your current one looks between 01 and 59

edit:

http://www.artfulsoftware.com/infotree/queries.php#78

you want to be doing something like that and then grouping by hour(datetime)

于 2013-08-27T12:03:31.253 回答