sql server - SQL Query check result with other rows in same table -


i want build sql query select row based on date range , want additional columns following sample table

+----+--------------+--------------+--------------+--------------+ | id | customerid   | accountid    |  datefrom    |    dateto    | +----+--------------+--------------+--------------+--------------+ |  1 | c0001        | a0001        | 21/01/2016   | 28/01/2016   | |  2 | c0001        | a0001        | 01/02/2016   | 08/02/2016   | |  3 | c0002        | a0002        | 09/02/2016   | 16/02/2016   | |  4 | c0002        | a0002        | 14/01/2016   | 21/01/2016   | |  5 | c0003        | a0003        | 07/01/2016   | 14/01/2016   | |  6 | c0003        | a0003        | 09/02/2016   | 16/02/2016   | |  7 | c0004        | a0004        | 01/01/2016   | 07/01/2016   | |  8 | c0004        | a0004        | 09/03/2016   | 16/03/2016   | +----+--------------+--------------+--------------+--------------+ 

if if pass date range 01/02/2016 28/02/2016 need result follows

+----+-------------+------------+--------------+--------------+-------------+ | id | customerid  | accountid  |  datefrom    |  dateto      |  isprevious | +----+-------------+------------+--------------+--------------+-------------+ |  1 | c0001       | a0001      | 01/02/2016   |  08/02/2016  |    yes      | |  2 | c0002       | a0002      | 09/02/2016   |  16/02/2016  |    yes      | |  3 | c0003       | a0003      | 09/02/2016   |  16/02/2016  |    yes      | +----+-------------+------------+--------------+--------------+-------------+ 

this asume want data full contain , no overlaps target range. assume none of row ranges overlap each other.

select t1.*,         case when (select 1                    yourtable t2                   t2.datefrom < t1.datefrom                     , t2.customerid  = t1.customerid                       , t2.accountid = t1.accountid ) null             'no'             else 'yes'        end isprevious  yourtable t1  datefrom <= '2016-02-28' ,       dateto >= '2016-02-01'; 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -