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.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 how to select longest and active row

Author  Topic 

satish15385
Starting Member

17 Posts

Posted - 2012-08-07 : 12:07:51
emplid -- payplan -- Termid -- Contractperiod -- datepayend
24 -- 22 -- 201205 -- UA -- 2012-06-07
24 -- 22 -- 201205 -- UB -- 2012-07-05

I want to select the contractperiod based on following conditions:
if it has more than one appointment (case like here) and contractperiod in ('UA','UB') then
the longest hire date from the date 2012-05-07 has to be selected
if datepayend is same then max(contractperiod) has to be selected

let me know your inputs

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-08-07 : 12:22:50
[code]
SELECT *
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY emplid,payplan ORDER BY datepayend DESC,ContractPeriod DESC) AS Seq,
COUNT(CASE WHEN contractperiod IN ('UA','UB') THEN 1 ELSE NULL END) OVER (PARTITION BY emplid,payplan) AS Occ,
*
FROM Table
)t
WHERE Seq=1
OR Occ<=1
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -