[英]Get Maximum value column from subquery mysql
i have a mysql query as我有一个 mysql 查询为
SELECT date,shortcode,SUM(count) as myCount
FROM mytable
WHERE smsc='123'
AND username NOT REGEXP '[A-Za-z]+'
AND DATE(date) >= CURDATE() - INTERVAL 7 DAY
GROUP BY shortcode,date
ORDER BY date ASC
Which gives the result as following which is perfectly fine结果如下,非常好
date日期 | shortcode短代码 | myCount我的计数 |
---|---|---|
2021-02-18 2021-02-18 | 123 123 | 7 7 |
2021-02-18 2021-02-18 | 231 231 | 15 15 |
2021-02-19 2021-02-19 | 783 783 | 117 117 |
2021-02-19 2021-02-19 | 894 894 | 115 115 |
2021-02-20 2021-02-20 | 009 009 | 70 70 |
2021-02-20 2021-02-20 | 565 565 | 15 15 |
now what i want to do is get max value of maxcount from each day and corresponding shortcode so what i did is现在我想做的是从每天获取 maxcount 的最大值和相应的简码,所以我所做的是
Select date,Max(myCount) as maxim,shortcode
from ( SELECT date,shortcode,SUM(count) as myCount
FROM mytable
WHERE smsc='123'
AND username NOT REGEXP '[A-Za-z]+'
AND DATE(date) >= CURDATE() - INTERVAL 7 DAY
GROUP BY shortcode,date
ORDER BY date ASC ) as a
GROUP BY a.date;
which is not giving me the right result my desired result is这没有给我正确的结果我想要的结果是
date | shortcode | maxim
2021-02-18 | 231 |15
2021-02-19 | 783 |117
2020-02-20 | 009 |70
You can use common table expression and row_number() to achieve your desired result:您可以使用公用表表达式和 row_number() 来实现您想要的结果:
with cte as (
select date,shortcode,mycount,row_number()over(partition by date order by mycount desc) rn from (SELECT date,shortcode,SUM(count) as myCount
FROM mytable
WHERE smsc='123'
AND username NOT REGEXP '[A-Za-z]+'
AND DATE(date) >= CURDATE() - INTERVAL 7 DAY
GROUP BY shortcode,date )t)
select date,shortcode,mycount from cte where rn=1
This query will generate a sequence for each date orderring by mycount in descendent order.此查询将按 mycount 以降序为每个日期排序生成一个序列。 So always the first row for each date will contain the max mycount.因此,每个日期的第一行总是包含最大 mycount。
If you can use a variable, the query is:如果可以使用变量,则查询为:
SET @x='';
SELECT
@x:=date,shortcode,myCount FROM (
SELECT date,shortcode,SUM(count) as myCount
FROM mytable
WHERE smsc='123'
AND username NOT REGEXP '[A-Za-z]+'
AND DATE(date) >= CURDATE() - INTERVAL 7 DAY
GROUP BY shortcode,date
ORDER BY date ASC,myCount DESC
) a
WHERE @x<>date
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.