Retrieve parent child records in SQL Server -
i have 2 tables trade
, trade details
this:
trade table:
id portfolio source version createdon status --------------------------------------------------------- 1 test1 rim 1.0 2016-01-20 1 2 test2 ios 1.0 2016-01-20 1
trade details table:
id tradeid ticker company shares action comments ---------------------------------------------------------------- 1 1 msft microsoft 100 buy test 2 1 ibm ibm 200 sell test 3 2 yahoo yahoo inc 50 sell test 4 2 goog google inc 500 buy test
i want retrieve , show data in following format.
output
1 test1 rim 1.0 2016-01-20 1 1 1 msft microsoft 100 buy test 2 1 ibm ibm 200 sell test 2 test2 ios 1.0 2016-01-20 1 3 2 yahoo yahoo inc 50 sell test 4 2 goog google inc 500 buy test
you need use union between 2 tables, , add additional columns customized, set desired order generate required output
ex [in oracle syntax, idea same]
select case when oid = 0 to_char(p_tradeid) else portfolio end tradeid, portfolio, ticker, company,shares, action, comments ( select id oid, 1 soid, tradeid p_tradeid, to_char(id) portfolio, -- important change datatype of columns matching in union in order union statement work ticker, company, to_char(shares) shares, to_char(action) action, comments ( --here select statement.... below demo select 1 id, 1 tradeid, 'msft' ticker, 'microsoft' company, 100 shares, 'buy' action, 'test' comments dual union select 2 id, 1 tradeid, 'ibm' ticker, 'ibm' company, 200 shares, 'sell' action, 'test' comments dual union select 3 id, 2 tradeid, 'yahoo' ticker, 'yahoo inc' company, 50 shares, 'sell' action, 'test' comments dual union select 4 id, 2 tradeid, 'goog' ticker, 'google inc' company, 500 shares, 'buy' action, 'test' comments dual ) union --the trick union here select 0 oid,0 soid, --and order columns here , in above query id p_tradeid, portfolio, source ticker, version company, to_char(createdon) shares, to_char(status) action, '' comments ( --and again, make sure datatype of columns same! select 1 id, 'test1' portfolio, 'rim' source, '1.0' version, '2016-01-20' createdon, 1 status dual union select 2 id, 'test2' portfolio, 'ios' source, '1.0' version, '2016-01-20' createdon, 1 status dual ) ) order p_tradeid, soid, oid
this generate following:
1 | test1 | rim | 1.0 | 2016-01-20 | 1 | 1 | 1 | msft | microsoft | 100 | buy | test 2 | 2 | ibm | ibm | 200 | sell | test 2 | test2 | ios | 1.0 | 2016-01-20 | 1 | 3 | 3 | yahoo | yahoo inc | 50 | sell | test 4 | 4 | goog | google inc | 500 | buy | test
see this sql fiddle link sql-server-2008 syntax
Comments
Post a Comment