获取包含SQL Server中最大值的行

时间:2014-07-19 08:27:49

标签: sql sql-server

我在SQL Server中有包含销售数据的表,如下所示。

seq_no  Itemid  Unit    pcs value
------------------------------------   
1       501     101     1   1001.48
1       502     102     2   1004.25
1       502     102     7    987.58
1       503     103     3    787.58
1       503     103     7    647.87
1       503     103     9   1478.58
1       504     104     2    202.25
1       504     104     3    365.87
1       504     104     7    102.25
1       504     104     6    322.22
1       505     105     1   2000.01
1       505     105     2    914.02

现在我想要单位明智的最大值记录。意思是当我在seq_no, itemid, unit上分组并获得pcs和值的总和时,它给出的结果如下。

项目摘要

seq_no   itemid  unit  pcs   value
------------------------------------
1        501     101    1   1001.48
1        502     102    9   1991.83
1        503     103   19   2914.03
1        504     104   12    992.59
1        505     105    3   2914.03

现在你可以看到,我有两个不同的记录,它们具有最大值(2914.03)(例如第3和第5条记录)。我需要第3条记录,因为它具有最大值的最大值。就我而言,我想要关注:

seq_no   itemid  unit  pcs   value
-------------------------------------
1        503     105    19  2914.03

如何在不损害性能的情况下获得此结果,因为此表包含很多行?

5 个答案:

答案 0 :(得分:2)

试试这个。

<强> QUERY

SELECT TOP 1 seq_no,
item_id,unit,
SUM(pcs) AS 'pcs',
SUM(value) AS 'value'
FROM tbl1
GROUP BY item_id,seq_no,unit
ORDER BY value DESC,pcs DESC

SQL FIDDLE HERE

答案 1 :(得分:1)

SELECT TOP 1 *
FROM   itemwise_summary
ORDER BY value desc, pcs desc

答案 2 :(得分:0)

试试这个。

WITH res AS  (

SELECT ROW_NUMBER()OVER (ORDER BY seq_no)rnum, 
seq_no,ItemID,unit,SUM(pcs)sum_pcs,SUM(VALUE)sum_val FROM tbl_name 
GROUP BY seq_no,ItemID,unit
)

SELECT TOP  1 * FROM res ORDER BY sum_pcs DESC,sum_val DESC

答案 3 :(得分:0)

试试这个

select max(value),* from table 

答案 4 :(得分:-1)

尝试,

CREATE TABLE tbl1(seq_no int,item_id int,Unit int,pcs int,value bigint);

insert into tbl1 VALUES(1,501,101,1,1001.48);
insert into tbl1 VALUES(1,502,102,2,1004.25);
insert into tbl1 VALUES(1,502,102,7,987.58);
insert into tbl1 VALUES(1,503,103,3,787.58);
insert into tbl1 VALUES(1,503,103,7,647.87);
insert into tbl1 VALUES(1,503,103,9,1478.58);
insert into tbl1 VALUES(1,504,104,2,202.25);
insert into tbl1 VALUES(1,504,104,3,365.87);
insert into tbl1 VALUES(1,504,104,7,102.25);
insert into tbl1 VALUES(1,504,104,6,322.22);
insert into tbl1 VALUES(1,505,105,1,2000.01);
insert into tbl1 VALUES(1,505,105,2,914.02);
select * from tbl1;



with cte(seq_no,a,b,c,d)as(
select x.seq_no ,x.item_id,x.Unit,sum(x.pcs),sum(x.value) from  (
select seq_no,item_id,Unit,pcs,value ,
ROW_NUMBER() over (partition by unit order by value) as rnk
from tbl1
)x group by  x.seq_no,x.item_id,x.Unit
)select seq_no,sum(a)/5 as item_id,MAX(b)as Unit, MAX(c)as pcs,MAX(d)as value from cte
group by seq_no

这个正在进行正确的检查。