3

Have this table (top row is column names):

security    quote_type      price
sec_1       bid             3.4
sec_1       ask             3.6
sec_2       bid             5.2
sec_2       ask             5.4
sec_3       bid             2.3
sec_4       ask             7.8

Need a query to achieve these results:

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

Using SQL Server.

Thanks for any help!

3
  • 2
    What if there will be more than 1 bid per security? Commented Dec 2, 2017 at 15:48
  • For just one pair of bid, ask per security you can use conditional aggregation to get the expected result. You can find plenty of similar cases here in SO. Commented Dec 2, 2017 at 16:21
  • There will be at most one bid and one ask per security Commented Dec 2, 2017 at 16:40

2 Answers 2

2

You can also just use conditional aggregation or pivot:

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;
Sign up to request clarification or add additional context in comments.

Comments

0

You could join between two queries on the table:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.