SQL查询以获取每天的最大值

时间:2018-05-31 22:06:44

标签: sql sql-server max

所以我有一个看起来像这样的表:

enter image description here

现在,我想要两天的最大totalcst,如下所示:

enter image description here

我尝试使用max和Row_number功能的不同变体但仍然无法获得我想要的结果。我的问题:

select date,pid,max(quan*cst), totalcst
from dbo.test1
group by date, pid

但这会返回所有记录。因此,如果有人能指出我正确的方向,那将非常有帮助。

提前致谢!

2 个答案:

答案 0 :(得分:1)

ROW_NUMBER应该可以正常工作:

WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY [date] ORDER BY totalcst)
    FROM dbo.YourTable
)
SELECT  [date],
        pid,
        totalcst
FROM CTE
WHERE RN = 1
;

答案 1 :(得分:0)

这是一个简单的方法:

select t.*
from test1 t
where t.totalcst = (select max(t2.totalcst) from test1 t2 where t2.date = t.date);

如果您在(date, totalcst)上有索引,这通常会获得最佳效果。当然,row_number() / rank()也是一个非常可接受的解决方案:

select t.*
from (select t.*, row_number() over (partition by date order by totalcst desc) as seqnum
      from test1
     ) t
where seqnum = 1;
相关问题