如何找到每个商店ID与相关日期的最大值?

问题描述 投票:0回答:1

我试图根据每个商店 ID 与相关日期的每日总计来查找最大总数量,但它没有按我预期的方式显示

这是我尝试过的:


select dateadd(dd,0,datediff(dd,0,Time)), storeid, max(qty_sum)
from
(
select time, storeid, sum(quantity) as qty_sum from table1
group by time, storeid, Quantity
) a  
group by dateadd(dd,0,datediff(dd,0,Time)), storeid
order by max(qty_sum) desc 

我不确定我做错了什么,但它仍然给我重复的商店 ID

sql sum max
1个回答
0
投票

您在内部子查询中同时按时间和 storeid 进行分组,您应该在内部子查询中仅按日期和 storeid 进行分组。 试试这个:

SELECT dateadd(dd,0,datediff(dd,0,time)) as date, storeid, MAX(qty_sum) as max_qty_sum
FROM
(
    SELECT dateadd(dd,0,datediff(dd,0,time)) as time, storeid, sum(quantity) as qty_sum
    FROM table1
    GROUP BY dateadd(dd,0,datediff(dd,0,time)), storeid
) a  
GROUP BY dateadd(dd,0,datediff(dd,0,time)), storeid
ORDER BY max_qty_sum DESC;
© www.soinside.com 2019 - 2024. All rights reserved.