【问题标题】:Query with date period and more查询日期时间段等
【发布时间】:2011-09-01 18:04:06
【问题描述】:

假设我们有一个名为 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) 此外,我想对 f2, r0.5, t*4 DESC 的最大总和进行排序:

C)此外,我只想计算特定时期内的事件数量,例如上周、一个月、过去 6 个月。您可以将以下 SQL 查询嵌入到您的答案中吗?是否有更多类型的间隔,例如月年或小时?

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

【问题讨论】:

    标签: mysql sql


    【解决方案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;
    

    【讨论】:

    • #1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册以获取正确的语法,以便在第 3 行使用 'text) as f,2*count(1) as f_sum from table1 where date >=current_date-30'
    • 糟糕,我搞砸了cast() 的语法。我已经进行了编辑。
    • 对不起另一个:#1052 - 字段列表中的列“名称”不明确
    • 奇怪...这不应该发生,因为我正在使用 name 进行所有连接。没关系,我已经进行了编辑。
    • 非常感谢。 1.最后一件事可能是“cast(count(1) as text)”必须更改为“cast(count(*) as unsigned integer)”。 2.我得到的每列和每行都是“1”。
    猜你喜欢
    • 2018-05-31
    • 2016-07-09
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2011-05-30
    • 2019-08-18
    • 2016-07-10
    • 2015-10-01
    相关资源
    最近更新 更多