sql server - SQL iterate for each group -


i have table:

|id| gruopid | status | date        | | 2| 1       | s1     | 7/29/2011   | | 3| 1       | s2     | 7/30/2011   | | 9| 1       | s1     | 8/02/2011   | | 7| 1       | s1     | 8/03/2011   | | 8| 1       | s1     | 8/04/2011   | | 1| 2       | s1     | 7/28/2011   | | 4| 2       | s2     | 7/30/2011   | | 5| 2       | s3     | 8/01/2011   | | 6| 3       | s1     | 8/02/2011   | 

and specific date outside source: 7/31/2011

i need query give me for each groupid closest upper , lower date, result be:

|id| gruopid | status | date        | | 3| 1       | s2     | 7/30/2011   | | 9| 1       | s1     | 8/02/2011   | | 4| 2       | s2     | 7/30/2011   | | 5| 2       | s3     | 8/01/2011   | | 6| 3       | s1     | 8/02/2011   | 

can please me , show me query?

straightforward approach:

select t1.id, t1.groupid, t1.status, t1.date mytable t1 t1.date in (     select max(t2.date)     mytable t2     t2.groupid = t1.groupid     , t2.date <= '7/31/2011'     union     select min(t3.date)     mytable t3     t3.groupid = t1.groupid     , t3.date >= '7/31/2011' ) 

please note number of rows per group may not two.

  • if there record precisely date 7/31/2011, single record returned group.
  • if records of group either before or after 7/31/2011, single record returned group.
  • if table contains duplicate combinations of groupid , date, more 2 rows may returned. inherent fact no 'correct' way choose between duplicates has been defined.

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -