Thursday 1 February 2018

Select records where having minimum costs.


create table #temp
(
id int,
Name varchar(10),
Cost int
)
insert into #temp 
values
(1,'x',5),
(1,'z',4),
(2,'y',6),
(3,'x',2),
(3,'y',5),
(3,'z',8)
select * from #temp
Select tbl.* From #Temp tbl
Inner Join
(
  Select Id,MIN(cost) MinCost From #Temp Group By Id
)tbl1
On tbl1.id=tbl.id
Where tbl1.MinCost=tbl.Cost

2 comments:

  1. with cte as
    (
    select *,DENSE_RANK() over (partition by id order by cost ) as costnew from #temp
    )
    select id,name,cost from cte where costnew=1

    ReplyDelete