Query to select from two different tables

Posted by ryan on Stack Overflow See other posts from Stack Overflow or by ryan
Published on 2014-06-06T03:15:04Z Indexed on 2014/06/06 3:24 UTC
Read the original article Hit count: 191

Filed under:

I would like to select from two tables and display my result using this query:

CREATE TABLE Buy_Table 
(
 buy_id int identity primary key, 
 user_id int, 
 amount decimal (18,2)
);
go
INSERT INTO Buy_Table 
(user_id, amount)
VALUES
('1', 10),
('1', 8),
('1', 20),
('3', 1),
 ('2', 2);
go
CREATE TABLE Sell_Table 
(
 sell_id int identity primary key, 
 user_id int, 
 amount decimal (18,2)
);
 go
 INSERT INTO Sell_Table 
 (user_id, amount)
 VALUES
 ('1', 10),
 ('1', 8),
 ('1', 20),
 ('3', 3),
 ('2', 3);
 go

select 
[user_id],
'Buy' as [Type],
buy_id as [ID],
amount

from Buy_Table

union all

select
[user_id],
'Sell',
sell_id,
amount
 from Sell_Table

order by
[user_id],
 [ID],
[Type]

However the above query will return each row of the user_id like this

enter image description here

I want to display my result to something like this in a grid:

enter image description here

Can this be done in query itself rather manipulating the grid? Thx

© Stack Overflow or respective owner

Related posts about sql