2016-11-24 73 views
0

我有一个表是这样的:SQL返回量最高和最低的价格

CREATE TABLE customerQuote(
          quoteID char(36) NOT NULL PRIMARY KEY 
          ,customerID char(36) NOT NULL 
          ,quoteNo INT 
          ,volume int 
          ,price decimal(6,2) 
          ); 
  • 一个customerID有许多quoteNo
  • 每个quotNo都有很多条目。
  • 价格和数量会有所不同。
  • 相同的quoteNo也可能有多个条目用于同一卷,但价格不同。

现在我需要返回customerIDquoteNo,成交量最高的和最低的价格上销量最高的查询。

一个例子: 一位顾客(的customerID)的报价: quoteNo=55 and quoteNo=62

这些报价有这些项:

quoteNo=55; volume=90; price=1.52 
quoteNo=55; volume=25; price=1.65 
quoteNo=55; volume=90; price=1.50 
quoteNo=62; volume=99; price=1.40 

对于这个特定的客户我想查询返回:

customerID, 55, 90, 1.50 
customerID, 62, 99, 1.40 

是的,我知道系统是混乱的,因为它允许同一个客户与sa我的音量,但这是现实生活中,我需要这个查询的原因。

+0

此Ref。到sql server 2012. –

+0

你到目前为止尝试过什么? – iamdave

+0

我尝试了MAX和MIN的不同组合,但最终列出了错误的组合。 –

回答

1

您可以派生表做到这一点:

with mv -- The derived table finds the quote with the highest volume. 
as 
(
    select customerID 
      ,quoteNo 
      ,max(volume) as maxVolume 
    from customerQuote 
    group by customerID 
      ,quoteNo 
) 
select c.customerID  -- Which you then use to find the lowest price at that volume. 
     ,c.quoteNo 
     ,mv.maxVolume 
     ,min(c.price) as minPrice 
from customerQuote c 
    inner join mv 
     on c.customerID = mv.customerID 
      and c.quoteNo = mv.quoteNo 
      and c.volume = mv.maxVolume 
group by c.customerID 
     ,c.quoteNo 
     ,mv.maxVolume;