0

I am trying to filter max(row_number). But getting errors. over partition by... order by code_description desc does not work for me. I have to get last code_id description. Right we can't keep aggregate function on where condition.I have imported records from excel

Help is much appreciated.

Expectation

Code_Id Code_description 10000, Maintain healthy bone,teeth and increase immune

My code is:

Create table #test 
(
    code_id int,
    Code_description varchar(100)
)

insert into #test values (10000, 'Maintain healthy bone')
insert into #test values (10000, 'Maintain healthy teeth')
insert into #test values (10000, 'Increases Immune')
insert into #test values (10000, 'Maintain healthy bone,teeth and increase immune')

With cte as
(
    select 
        code_id, Code_description,
        row_number() over (partition by code_ID order by code_id) rn
    from 
        #test
)
select * 
from cte 
where rn = max(rn)
group by code_id, Code_description
SQL2023
  • 29
  • 5
  • "*I have to get last code_id description*" - do you have to get last code_id or do you have to get last Code_description? – lemon Oct 16 '22 at 16:39
  • Can you post what is the expected output? – Agar123 Oct 16 '22 at 16:47
  • I have to get max(rn) code_description – SQL2023 Oct 16 '22 at 16:52
  • You can set a colum to generete auto incremental ID and filter like below: Create table #test ( code_id_flag int identity (1,1), code_id int, Code_description varchar(100) ) insert into #test values (10000, 'Maintain healthy bone') insert into #test values (10000, 'Maintain healthy teeth') insert into #test values (10000, 'Increases Immune') With cte as ( select * from #test ) select code_id, Code_description from cte where code_id_flag = (SELECT MAX(code_id_flag) FROM #test) order by code_id_flag; – jMarcel Oct 16 '22 at 17:02

0 Answers0