简体   繁体   中英

How to get the unique set of count for rows with different values for a certain hour

select id, hour, count from stats;

1, 0, 2
2, 0, 20
3, 1, 10
4, 1, 20 
5, 2, 10
5, 2, 30

I would want the output (hour, count) to render as

0, 22
1, 30
2, 40

How do I perform a unique count for the hour interval?

You can make use of the group by clause:

SELECT  hour, count(id)
GROUP BY hour;

So for this dataset:

1, 0, 2
2, 0, 20
3, 1, 10
4, 1, 20 
5, 2, 10
5, 2, 30

you will get

0, 2
1, 2
2, 2

If you want to get the sum for that hour use SUM()

SELECT  hour, sum(`count`)
GROUP BY hour;

NOTE: Try not to use the word count as a field name because it is also a key word in mysql

select hour, sum(count)
from stats
group by hour

You need to use SUM() function to achieve that:

SELECT hour, sum(`count`) AS `TotalCOUNT`
FROM stats
GROUP BY hour

See this SQLFiddle

I would like to go for SELECT hour,sum(count) FROM stats GROUP by hour;

Here is the reference for group by clause http://www.techonthenet.com/sql/group_by.php

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