我如何构造一个sql来查找每个产品在不同日期和时间的最大数量?

efzxgjgh  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(364)

请我需要一个sql找到每个产品的最大qntt,并知道日期和时间。

+-----------+--------+-----------+-----------+
| Product   |  QNTT  |   date    |    hour   |
+-----------+--------+-----------+-----------+
|       AAA |     31 | 28-nov-18 |     09    |
|       AAA |     21 | 28-nov-18 |     10    |
|       AAA |     52 | 28-nov-18 |     11    |
|       AAA |     11 | 28-nov-18 |     12    |
|       AAA |     15 | 29-nov-18 |     09    |
|       AAA |     19 | 29-nov-18 |     10    |
|       AAA |     22 | 29-nov-18 |     11    |
|       AAA |     33 | 29-nov-18 |     12    |
|       AAA |     55 | 30-nov-18 |     09    |
|       AAA |     42 | 30-nov-18 |     10    |
|       AAA |     31 | 30-nov-18 |     11    |
|       AAA |     21 | 30-nov-18 |     12    |
|       BBB |     31 | 28-nov-18 |     09    |
|       BBB |     21 | 28-nov-18 |     10    |
|       BBB |     12 | 28-nov-18 |     11    |
|       BBB |     58 | 28-nov-18 |     12    |
|       BBB |     15 | 29-nov-18 |     09    |
|       BBB |     19 | 29-nov-18 |     10    |
|       BBB |     22 | 29-nov-18 |     11    |
|       BBB |     33 | 29-nov-18 |     12    |
|       BBB |     43 | 30-nov-18 |     09    |
|       BBB |     42 | 30-nov-18 |     10    |
|       BBB |     51 | 30-nov-18 |     11    |
|       BBB |     21 | 30-nov-18 |     12    |
+-----------+--------+-----------+-----------+

我想要的sql答案都是产品的最大值(qntt):

+-----------+--------+-----------+-----------+
| Product   |  QNTT  |   date    |    hour   |
+-----------+--------+-----------+-----------+
|       AAA |     55 | 30-nov-18 |     09    |
|       BBB |     58 | 28-nov-18 |     12    |
+-----------+--------+-----------+-----------+

我可以在没有时间和日期的情况下找到结果:

SELECT
    Product, max(QNTT)
FROM
    TABLE 
WHERE  
    Month(DATE) = 11 AND YEAR(DATE) = 2018 
AND
    Product <> 'AAAB' 
AND
    Substr(Product, 1, 3) IN ('AAA','BBB') 
AND
    hour<= 18 
AND
    Day(DATE) > 13   
GROUP BY
    Product  
ORDER BY
    Product, QNTT DESC

但是我需要日期和时间来知道每个月的最大数字是什么时候。

bwntbbo3

bwntbbo31#

你可以使用 subquerygroup by Product 作为:

select *
  from tab 
 where ( Product, QNTT ) in
(select Product, max(QNTT)
   from tab
  group by Product ) t

相关问题