简体   繁体   English

SQL查找日期有最大记录

[英]SQL to find day have max records

I have a tbl_transaction table in MySQL database. 我在MySQL数据库中有一个tbl_transaction表。 with format like below: 格式如下:

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

I want to write SQLs to 我想写SQL

  1. to find the Day which have count of records ( in table tbl_transaction) is max 查找具有记录计数的天(在表tbl_transaction中)最大
  2. to find the Hour which have count of records ( in table tbl_transaction) is max 查找具有记录计数的小时(在表tbl_transaction中)最大

Thanks 谢谢

Try this for sql server.. 尝试此为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 对于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)))

Count By Date: 按日期计数:

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

Count By Hour: 按小时计数:

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

You would use group by , order by , and limit . 您将使用group byorder bylimit For the date: 对于日期:

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

For the hour (assuming you mean hour and day): 对于小时(假设您指的是小时日期):

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM