同一表的列上的SQL联接
具有此表(顶行为列名): 需要查询以获得这些结果:同一表的列上的SQL联接,sql,sql-server,Sql,Sql Server,具有此表(顶行为列名): 需要查询以获得这些结果: security bid ask sec_1 3.4 3.6 sec_2 5.2 5.4 sec_3 2.3 null sec_4 null 7.8 使用SQL Server 谢谢你的帮助 您可以在表上的两个查询之间联接: SELECT a.security, bid, ask FROM (SELECT secu
security bid ask
sec_1 3.4 3.6
sec_2 5.2 5.4
sec_3 2.3 null
sec_4 null 7.8
使用SQL Server
谢谢你的帮助 您可以在表上的两个查询之间联接:
SELECT a.security, bid, ask
FROM (SELECT security, price AS bid
FROM mytable
WHERE quote_type = 'bid') a
FULL OUTER JOIN (SELECT security, price AS ask
FROM mytable
WHERE quote_type = 'ask') b ON a.security = b.security
您也可以只使用条件聚合或透视:
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;
如果每个证券将有超过1个出价怎么办?对于每个证券只有一对
bid
,ask
,您可以使用条件聚合来获得预期结果。你可以在这里找到很多类似的案例。每个证券最多有一次出价和一次询问
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;