简体   繁体   中英

Group by date hour in sql

halo, i want to add id then group by product and date hour(without change the datetime to varchar). with data is:

datetime               product    sold
2020-10-27 08:51:00       A        50
2020-10-27 08:52:00       A        10
2020-10-27 08:52:00       B        20
2020-10-27 09:52:00       B        30

my query is:

select newId() as id, datehour(datetime) datehour, product, sum(sold)
from table_a
group by datehour(datetime), product

but did not work

my expected result:

note: the date hour should be datetime type not varchar

id   datehour               product    sold
1    2020-10-27 08:00:00       A        60
2    2020-10-27 08:00:00       B        20
3    2020-10-27 09:00:00       B        30

note: the date hour should be datetime type not varchar

any idea?

It's not clear what you're trying to achieve with newId() . Other than that, you can get the result you want by using DATE_FORMAT and STR_TO_DATE to strip the minutes and seconds from the times to get the datehour value; you can then GROUP BY that and product and SUM the sold values:

SELECT STR_TO_DATE(DATE_FORMAT(`datetime`, '%Y-%m-%d %H'), '%Y-%m-%d %H') AS datehour,
       product,
       SUM(sold) AS sold
FROM table_a
GROUP BY datehour, product

Output:

datehour                sold    product
2020-10-27 08:00:00     60      A
2020-10-27 08:00:00     20      B
2020-10-27 09:00:00     30      B

Demo on db-fiddle

In terms of generating the id value, if you are using MySQL 8+ you can use ROW_NUMBER() :

SELECT ROW_NUMBER() OVER (ORDER BY datehour, product) AS id,
       datehour,
       product,
       sold
FROM (
  SELECT STR_TO_DATE(DATE_FORMAT(`datetime`, '%Y-%m-%d %H'), '%Y-%m-%d %H') AS datehour,
         product,
         SUM(sold) AS sold
  FROM table_a
  GROUP BY datehour, product
) a
ORDER BY id

For MySQL 5.x, you can simulate ROW_NUMBER() with a variable:

SELECT @rn := @rn + 1 AS id,
       datehour,
       product,
       sold
FROM (
  SELECT STR_TO_DATE(DATE_FORMAT(`datetime`, '%Y-%m-%d %H'), '%Y-%m-%d %H') AS datehour,
         product,
         SUM(sold) AS sold
  FROM table_a
  GROUP BY datehour, product
  ORDER BY datehour, product
) a
CROSS JOIN (SELECT @rn := 0) i

In both cases the output is:

id  datehour                product     sold
1   2020-10-27 08:00:00     A           60
2   2020-10-27 08:00:00     B           20
3   2020-10-27 09:00:00     B           30

Demo on db-fiddle

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