获取列的不同以及两个不同列的最大值和最小值,并将其作为单个记录返回

时间:2014-06-13 16:08:58

标签: sql sql-server sql-server-2012

我有一个包含多个列和行的表,我在表上执行了一些数学计算,并使用以下SQL视图将它们作为不同的表返回

CREATE VIEW [dbo].[XYZ]
AS
with numbered as
(
    select 
        id, 
        product,  
        term, 
        bid, 
        offer, 
        termid,
        productid, 
        bidVolume,
        offerVolume, 
        row_number() OVER (Partition BY Product ORDER BY termid ) i
    from  dbo.abc
)

select 
    Row_number() over(order by r1.i)  as Id, 
    r1.Product + '/' + r2.Product as Market, 
    r1.term as Term, 
    r1.Bid - r2.Offer [Bid], 
    r1.Offer - r2.Bid [Offer]
from numbered r1 
join numbered r2 
    on   r1.Product != r2.Product 
    and r1.termid = r2.termid  
    and r1.term = r2.term 
    and r1.ProductID < r2.ProductID 
    and r1.Product Not like '%/%' 
    and r2.Product not like '%/%'

GO

我得到了以下结果

表1:

Id Market Term Bid Offer
1   A/B    Jan14  NULL NULL
2   A/B    jan14  NULL 20
3   A/B    Jan14  10  NULL
4   A/B    Jan14  5   10
5   X/Z    Mar14  10  12
6   X/Z    Mar14   8  9

从上面的结果我试图写一个查询,为每个市场和期限返回一行,最高出价和最低报价,如下所示

表2:

Id Market Term    Bid Offer
 1   A/B    Jan14  10 10
 2   X/Z    Mar14  10  9

PS:从上面的结果我们可以看出Id = 1的买入和卖出来自原始表的两个不同的记录,分别是最高和最低

1 个答案:

答案 0 :(得分:3)

如果我理解正确,您需要一个简单的group by

select row_number() over (order by (select NULL)) as id,
       market, term, max(bid) as Bid, min(offer) as offer
from XYZ
group by market, term;