简体   繁体   中英

How can I count the number of times an item occurs in a given date in mysql

So I have a table called violators, and I have 2 columns: Violation and Date. Violators:

---------------------------
Violation     | Date
---------------------------
overspeeding  | 2016-05-05
overloading   | 2016-05-07
overspeeding  | 2016-05-05
drunk driving | 2016-05-03

I want to know how many times the overspeeding occured in 2016-05-05, So the answer should be: 2016-05-05 - overspeeding - 2

And if I want to know, how many times the oversloading occured in 2016-05-07, The answer should be: 2016-05-07 - overloading - 1

there will be an entry in your table against every overspeeding record.

so execute a sql query (eg with php)

$resultset = select * from tablename where Violation ='overspeeding' And Date ='2016-05-05'

this will give you two record so simply apply a count function on result set.in mysql with php ,it will look like this

$temp_variable_no_of_overspeeding =mysql_num_rows($resultset); 
// or you can use count function if don't need those values

so will have 2 in your temp variable

i guess you are using java so do like this

ResultSet rs = ps.executeQuery();
int rowcount = 0;
if (rs.last()) {
  rowcount = rs.getRow();
  rs.beforeFirst(); // required to read data in while later . not rs.first() 
                    //because the rs.next() below will move on 2nd element ,
                    //you will miss the first element
}
while (rs.next()) {
  // do your standard per row stuff
}

I already fixed the problem: So here's the Sql query:

select Violation, count(Violation), Date_Violated from violators group by Violation, Date_Violated

Thank you guys for the help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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