0

I have a table in which I have few columns like below:

Cusnbr  Name  LoadNumber
 1       Z      10
 1       Z      9
 1       Z      8
 1       C      7
 1       C      6
 1       C      5
 1       B      4
 1       B      3
 1       A      2
 1       A      1

it is just for one cusnbr there are million of cusnbr like this..

I want output like below

Cusnbr  Name  LoadNumber
 1       C      7
 1       B      4
 1       A      2

For that I write below query in sql server 2008:

;With x as
 (
   Select * ,rn=Row_number() over (order by cusnbr,loadnumber) from table
 )
 select x.* from x left outer join x as y  on x.rn=y.rn+1
 and x.name<>y.name  where y.name is not null

but I am not getting the desired output in the above code I am getting last Z also which I don't want and I am getting irregular data not in the correct form in which I want

Any help will be appreciated !!

like this I want but not able to get the desired output

I use this example

Amitesh
  • 435
  • 3
  • 17

2 Answers2

0

Though the question is not clear to me , Guessing from the output I have tried out Dense Rank . I guessed you want the record with highest LoadNumber with the same name .

 Select * from cteTrial where LoadNumber in (
 Select MAX(x.LoadNumber) as LoadNumber from (
 Select cusnbr , name , LoadNumber , DENSE_RANK() over (order by Name desc ) 
 as Dense from cteTrial) as x group by x.Dense 
 ) 

If you can use CTE it will produce better performance .

Saronyo
  • 158
  • 7
0

i written the code as per expected

;With cte(Cusnbr , Name , LoadNumber)
AS
(
SELECT 1,'Z', 10 Union all
SELECT 1,'Z', 9  Union all
SELECT 1,'Z', 8  Union all
SELECT 1,'C', 7  Union all
SELECT 1,'C', 6  Union all
SELECT 1,'C', 5  Union all
SELECT 1,'B', 4  Union all
SELECT 1,'B', 3  Union all
SELECT 1,'A', 2  Union all  
SELECT 1,'A', 1
)
SELECT cusnbr, 
       NAME, 
       loadnumber 
FROM   (SELECT *, 
               Row_number() 
                 OVER( 
                   partition BY NAME 
                   ORDER BY loadnumber DESC) AS RNk, 
               Row_number() 
                 OVER( 
                   ORDER BY (SELECT 1)) - 1  AS RNO 
        FROM   (SELECT * 
                FROM   cte)dt)DT2 
WHERE  DT2.rnk = 1 
       AND rno > 0 
ORDER  BY NAME DESC 

Result

cusnbr  NAME    loadnumber
-------------------------
1        C          7
1        B          4
1        A          2
Sreenu131
  • 2,476
  • 1
  • 7
  • 18