简体   繁体   中英

Count unrepeated elements on mysql group by

I have the following table:

| id | metrictimestamp | vehicleid |
+----+-----------------+-----------+
|  1 |  20180201025934 |     33089 |
|  2 |  20180201025955 |     34489 |
|  3 |  20180201025959 |     32040 |

I need to group by date(metrictimestamp) and count how many unrepeated "vehicleid" there is for each day, any sugestions?

You can use DISTINCT in your query:

SELECT COUNT(DISTINCT metrictimestamp) FROM yourTable

First you need to convert your metrictimestamp field into a date type that mysql understands:

STR_TO_DATE(metrictimestamp, '%Y%m%d%h%i%s')

next you need to extract the date portion of that field and give it an alias (date):

DATE(STR_TO_DATE(metrictimestamp, '%Y%m%d%h%i%s')) date

finally you need to group by the resultant date and the vehicleid and filter by repeated records (so only include singletons), so putting it all together:

select DATE(STR_TO_DATE(metrictimestamp, '%Y%m%d%h%i%s')) date, vehicleid from group_test_table group by date, vehicleid having count(vehicleid) = 1;

If I misunderstood your question and you only want the unique vehicleids for any date then:

select distinct DATE(STR_TO_DATE(metrictimestamp, '%Y%m%d%h%i%s')) date, vehicleid from group_test_table group by date, vehicleid;

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