簡體   English   中英

查詢日期期間等

[英]Query with date period and more

假設我們有一個名為 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()

您可以只使用一些自連接(注意:這是未經測試的,因為我沒有安裝 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM