需要查询才能选择最低成本和最长日期

时间:2018-01-23 11:13:51

标签: sql-server sql-server-2008

我有一张表和这样的值

create table minmaxtest
(
id int,
mfg varchar(100),
mfgid varchar(100),
[Desc] varchar(100),
po_date date,
cost money
) 

insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (1,'abc','123','catheter','09/30/15',9)
insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (2,'abc','123','catheter','09/30/15',10)
insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (3,'abc','123','catheter','09/28/15',8)
insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (4,'abc','123','catheter','09/28/15',20)

insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (5,'xyz','666','stent','09/30/15',9)
insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (6,'xyz','666','stent','09/30/15',10)
insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (7,'xyz','666','stent','09/28/15',8)
insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (8,'xyz','666','stent','09/28/15',20)

我需要获得最大po_date和最低费用,如图enter image description here所示

我试过这样但没有得到适当的价值,任何帮助都会非常感激。

我的代码:

*select * from minmaxtest where po_date in(select max(po_date) from minmaxtest)
and cost in (select min(cost) from minmaxtest)*

2 个答案:

答案 0 :(得分:0)

试试这个

;with cte
as
(
SELECT 
    SequenceId = ROW_NUMBER() OVER(PARTITION BY mfg ORDER BY id),
    id,
    mfg,
    mfgid,
    [Desc],
    po_date = MAX(PO_Date) OVER(PARTITION BY mfgid),     
    cost = MIN(cost) OVER(PARTITION BY mfgid,po_date)
FROM minmaxtest
)
select
    *
    from cte
       where SequenceId = 1

我的结果

enter image description here

答案 1 :(得分:0)

;with cte as ( SELECT ROW_NUMBER() OVER(partition by mfg ORDER BY po_date desc, cost asc) as RN, id, mfg, mfgid, [Desc], po_date ,
cost FROM minmaxtest ) select id, mfg as Productmanufacturer, mfgid, [Desc] as ProductDescription, po_date ,
cost from cte where RN = 1

输出:

enter image description here