带有日期和更多的SQL查询

时间:2011-09-01 18:04:06

标签: sql phpmyadmin mysqli

假设我们有一个名为table1的表:

id  name    event    date
1   name1   f        2010-02-26 21:49:46
2   name2   f        2011-01-21 14:30:26
3   name3   f        2010-05-25 20:51:07
4   name2   r        2011-03-21 21:49:46
5   name4   t        2011-09-15 21:30:26
6   name2   t        2010-01-20 13:07:55
7   name2   t        2011-02-24 20:51:09
8   name1   r        2011-05-20 16:07:55
9   name2   r        2009-07-23 07:51:11
10  name2   r        2011-09-20 21:49:46

a)所以我希望结果在4列中:

name    f   r   t
name1   f:1 r:1 t:0
name2   f:1 r:3 t:2

b)而且我想要与f * 2,r * 0.5,t * 4 DESC的最大和相关:

c)而且我想计算仅在特定时期内的事件数量,例如上周,下个月,最后6个月。你可以嵌入下面的SQL查询来回答吗?是否有更多类型的间隔,如月份或小时?

SELECT *
FROM table1
WHERE date BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 WEEK) AND CURDATE()

提前致谢

1 个答案:

答案 0 :(得分:1)

你可以使用一些自联接(注意:这是未经测试的,因为我没有安装MySQL,但这应该有效。)

select a.name, f,r,t
from(
    select name, count(1) as f,2*count(1) as f_sum
    from table1
    where date >=current_date-30 --or whatever date range you want
    and event='f'
    group by name
    )a
join(
    select name, ,count(1) as r,0.5*count(1) as r_sum
    from table1
    where date >=current_date-30 --or whatever date range you want
    and event='r'
    group by name
    )b
on a.name=b.name
join(
    select name, count(1) as t,4*count(1) as t_sum
    from table1
    where date >=current_date-30 --or whatever date range you want
    and event='t'
    group by name
    )c
on b.name=c.name
order by f_sum+r_sum+t_sum desc;