查找日期的SQL有最大记录

时间:2014-12-20 07:08:00

标签: mysql sql

我在MySQL数据库中有一个tbl_transaction表。 格式如下:

tbl_transaction  (
    trans_id: int
    trans_time: timestamp
    amount: float
)

我想将SQL写入

  1. 查找记录数量的日期(在表tbl_transaction中)为max
  2. 查找具有记录计数的小时(在表tbl_transaction中)为max
  3. 由于

3 个答案:

答案 0 :(得分:0)

尝试使用sql server ..

SELECT datepart(dd,trans_time) AS DAY,
       datepart(hh,trans_time) AS Hours
FROM tbl_transaction
WHERE trans_id =
    (SELECT trans_id
     FROM tbl_transaction
     GROUP BY trans_id having count(trans_id)=max(count(trans_id)))

for Mysql

  SELECT Day(dd,trans_time) AS DAY,
           Hour(hh,trans_time) AS Hours
    FROM tbl_transaction
    WHERE trans_id =
        (SELECT max(trans_id)
         FROM tbl_transaction
          trans_id having count(trans_id)=max(count(trans_id)))

答案 1 :(得分:0)

按日期计算:

select 
    count(`trans_id`) as TCount,
    DATE(`trans_time`) as `Date`
from `tbl_transaction`
group by DATE(`trans_time`)

按小时计算:

select 
    count(`trans_id`) as TCount,
    HOUR(`trans_time`) as `Hour`
from `tbl_transaction`
group by HOUR(`trans_time`)

答案 2 :(得分:0)

您可以使用group byorder bylimit。对于日期:

select date(trans_time), count(*)
from tbl_transaction
group by date(trans_time)
order by count(*) desc
limit 1;

小时(假设你的意思是小时天):

select date(trans_time), hour(trans_time), count(*)
from tbl_transaction
group by date(trans_time), hour(trans_time)
order by count(*) desc
limit 1;