sql server - Should this T-SQL be done using a UNION -


using table below (call tablea), need create sql statement selects 2 sets of data , combines them together. first, need select rows status = 1 , datecreated greater (meaning newer) specified date, i'll call startdate. need select rows status = 0 , datecreated greater specified date results sorted datecreated descendingly , number of these records limited 2.

so if table data looks this:

id   status        datecreated 1      1         2013-05-01 14:00 2      1         2013-05-01 15:00 3      1         2013-05-01 16:00 4      0         2013-05-01 17:00 5      0         2013-05-01 18:00 6      0         2013-05-01 19:00 7      0         2013-05-01 20:00 

and set @startdate 2013-05-01 14:30, want result set this:

2      1         2013-05-01 15:00 3      1         2013-05-01 16:00 6      0         2013-05-01 19:00 7      0         2013-05-01 20:00 

is best done union joins 2 results or there better more efficient way?

you should benchmark real data set performance differences, give alternative can write using row_number() instead;

select id, status, datecreated (   select id, status, datecreated,       row_number() on (partition status order datecreated desc) rn   table1 datecreated > '2013-05-01 14:30' ) status = 1 or rn < 3 order datecreated; 

an sqlfiddle test with.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -