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)
 Need a help with SQL query

Author  Topic 

uditsingh89
Starting Member

1 Post

Posted - 2015-01-16 : 04:38:05
Hello

I need help to write a SQl query. Lets say I have a table test as -

Name Val
a 200
a 400
a 700
b 100
b 150
b 50
c 80
c 40
c 200

I need the result using select query only till Val is increasing for each name.
e.g.

Name Val
a 200
a 400
a 700
b 100
b 150
c 80


Can someone help me into this.

Ifor
Aged Yak Warrior

700 Posts

Posted - 2015-01-16 : 06:09:16
There is nothing here to indicate the order of the rows.

Do you have an ID or datetime column to give the order listed?

I think you have failed to understand that a table is an UNORDERED set.
Go to Top of Page

stepson
Aged Yak Warrior

545 Posts

Posted - 2015-01-16 : 07:05:18
Hi,

As Ifor said, we need a column that indicate the order of the records.
So , I added a column


;with aCTE (cID,Name,Val)
AS
(SELECT 1,'a',200 UNION ALL
SELECT 2,'a',400 UNION ALL
SELECT 3,'a',700 UNION ALL
SELECT 4,'b',100 UNION ALL
SELECT 5,'b',150 UNION ALL
SELECT 6,'b',50 UNION ALL
SELECT 7,'c',80 UNION ALL
SELECT 8,'c',40 UNION ALL
SELECT 9,'c',200 UNION ALL
SELECT 10,'c',220
)


SELECT
B.Name
,B.Val
FROM
(
SELECT A.*
, MIN(CASE WHEN A.Val>= ISNULL(prevRow.Val,A.Val) THEN 1 ELSE 0 END) OVER(PARTITION BY A.Name ORDER BY A.cID ASC) AS minID
FROM aCTE AS A
OUTER APPLY
( SELECT TOP (1) *
FROM aCTE AS B
WHERE A.Name = B.Name
AND A.cID > B.cID
ORDER BY B.cID DESC) AS prevRow
)B
WHERE B.minID = 1



and the output:

a 200
a 400
a 700
b 100
b 150
c 80




sabinWeb MCP
Go to Top of Page
   

- Advertisement -