Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
neeraj1401
Starting Member
36 Posts |
Posted - 2013-04-01 : 10:27:32
|
I’m having one table having two column ID and Segment. Create table test (id numeric ,segment numeric,created_on datetime) insert into test values (50708520,1,getdate())insert into test values (50708520,2,getdate())insert into test values (50708520,3,getdate())insert into test values (50708520,1,getdate())insert into test values (50708521,1,getdate())insert into test values (50708522,1,getdate())insert into test values (50708523,1,getdate())insert into test values (50708523,1,getdate())insert into test values (50708524,1,getdate())insert into test values (50708524,2,getdate())insert into test values (50708524,1,getdate())I want a query/procedure which will found id which have last and first segment matching for that ID on the basis of created_on. |
|
James K
Master Smack Fu Yak Hacker
3873 Posts |
Posted - 2013-04-01 : 10:59:39
|
Your explanation is not 100% clear to me, but something like this?select ID, segment_numeric, created_on, CASE WHEN FirstId = 1 then 'First' else 'Last' end as RankNumberfrom( select RANK() over (partition by id order by created_on asc) as FirstId, RANK() over (partition by id order by created_on desc) as LastId, * from Test)swhere FirstId = 1 or LastId = 1 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-04-01 : 11:52:54
|
If SQL 2012SELECT *FROM (SELECT *,FIRST_VALUE(segment) OVER (PARTITION BY id ORDER BY created_on) AS First,LAST_VALUE(segment) OVER (PARTITION BY id ORDER BY created_on) AS LastFROM Table)tWHERE First=Last ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-04-01 : 13:01:21
|
If below 2012 use this;With CTEAS(SELECT idFROM(SELECT *,ROW_NUMBER() OVER (PARTITION BY id ORDER BY created_on) AS Seq,ROW_NUMBER() OVER (PARTITION BY id ORDER BY created_on DESC) AS BSeqFROM Table)tWHERE Bseq=1OR Seq=1GROUP BY idHAVING COUNT(DISTINCT segment) =1)SELECT t.*FROM Table tJOIN CTE cON c.id = t.id ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
|
|
|
|
|