Click here to Skip to main content
15,896,475 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have list of records as given below in ms sql table
time	                       flag
2018-04-18 16:24:08.0000000     0
2018-04-18 16:14:08.0000000	1
2018-04-18 16:04:08.0000000	0
2018-04-18 15:54:08.0000000	0
2018-04-18 15:44:08.0000000	1
2018-04-18 15:34:08.0000000	1
2018-04-18 15:24:08.0000000	0
2018-04-18 15:04:08.0000000	1
2018-04-18 14:54:08.0000000	1
2018-04-18 14:44:08.0000000	0

how to get first occurrence of  flag 1 record(only one record that has occurred 1 st time based on time) and the last occurrence of flag 0 record(only one record that has occurred last)
Result  should be :
2018-04-18 14:54:08.0000000	1
2018-04-18 16:24:08.0000000	0
(two records)

or else 
2018-04-18 14:54:08.0000000	1   2018-04-18 16:24:08.0000000	0(single record)


What I have tried:

I have tried using Rownumber() function but i havent get expected result
Posted
Updated 21-Apr-18 0:02am
v3

Try:
SQL
SELECT CASE WHEN Flag = 1 THEN MAX([Time]) 
                          ELSE MIN([Time]) 
                          END AS [Time], 
       Flag
FROM MyTable 
GROUP BY Flag
 
Share this answer
 
v2
One way is to use a correlated NOT EXISTS condition. Something like
SQL
SELECT * 
FROM TableNameGoesHere t1
WHERE t1.Flag = 1
AND   NOT EXISTS ( SELECT 1
                   FROM TableNameGoesHere t2
                   WHERE t2.Flag = 1
                   AND   t2.Time < t1.Time)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900