SQL连接在同一个表的列上,另一列上有MAX

时间:2017-12-04 20:54:04

标签: sql sql-server

拥有此表(顶行是列名):

security    quote_type      price     round   
sec_1       bid             3.4       1
sec_1       ask             3.6       1
sec_1       bid             3.5       2
sec_1       ask             3.7       2
sec_2       bid             5.2       1
sec_2       ask             5.4       1
sec_3       bid             2.3       1 
sec_4       ask             7.8       1
sec_4       ask             7.9       2

需要实现这些结果:

security    bid     ask      round
sec_1       3.5     3.7      2 
sec_2       5.2     5.4      1
sec_3       2.3     null     1
sec_4       null    7.9      2

有这么多工作,还没有考虑到“圆形”栏目:

select security,
   max(case when quote_type = 'bid' then price end) as bid,
   max(case when quote_type = 'ask' then price end) as ask
from t
group by security;

每轮最多只有一次出价和一次要价。

使用SQL Server。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您似乎想要每个安全性的最大回合。这是一种方法:

select security,
       max(case when quote_type = 'bid' then price end) as bid,
       max(case when quote_type = 'ask' then price end) as ask
from (select t.*, max(round) over (partition by security) as max_round
      from t
     ) t
where round = max_round
group by security;

答案 1 :(得分:0)

创建表格并插入数据:

CREATE TABLE [security] (security VARCHAR(10),quote_type VARCHAR(10),price NUMERIC(3,1),round INT)

INSERT INTO [security]
SELECT 'sec_1','bid','3.4','1'
UNION SELECT 'sec_1','ask','3.6','1'
UNION SELECT 'sec_1','bid','3.5','2'
UNION SELECT 'sec_1','ask','3.7','2'
UNION SELECT 'sec_2','bid','5.2','1'
UNION SELECT 'sec_2','ask','5.4','1'
UNION SELECT 'sec_3','bid','2.3','1'
UNION SELECT 'sec_4','ask','7.8','1'
UNION SELECT 'sec_4','ask','7.9','2'

select * From [security]

请求结果:

  ;with cte_max_round as (
        SELECT security,MAX(Round) R FROM [security]
        group by security
        )

    SELECT B.security,BID.price,ASK.price,r Round 
    FROM cte_max_round B 
    LEFT JOIN [security] ASK 
        ON B.security = ASK.security AND B.R = ASK.[round] AND ASK.quote_type = 'ask' 
    LEFT JOIN [security] BID 
        ON B.security = BID.security AND B.R = BID.[round] AND BID.quote_type = 'bid'