Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
Dear allI am having table Table name is dist_salesDis_id Item_no sales_qty10 i1 1010 i2 23 10 i3 0510 i4 08 20 i1 0420 i2 0620 i3 29 20 i4 1020 i5 5530 i1 0930 i2 0730 i3 7730 i4 20ETC...........Like this is there are many distributor...I want get top three sales for each distributor in a single query in sql serverselect top 3 Dis_id ,Item_no,sales_qty from dist_saleswhere Dis_id=10 order by sales_qty descAbove query will work fine only for one distributor id.I want the query for the distributors in single query Please help me. This is very urgentThanks in AdvanceRaju
madhivanan
Premature Yak Congratulator
22864 Posts
Posted - 2005-03-24 : 06:06:39
declare SelectTop3 Cursorfor select distinct Dis_id from dist_salesOpen SelectTop3Declare @no nvarchar(2000)fetch next from SelectTop3 into @nowhile @@Fetch_Status<>-1beginset rowcount 3select * from dist_sales where dis_id=@nofetch next from SelectTop3 into @noend Deallocate SelectTop3MadhivananFailing to plan is Planning to fail
spirit1
Cybernetic Yak Master
11752 Posts
Posted - 2005-03-24 : 06:16:46
no cursors, please
Select Dis_id, Item_no, sales_qtyFrom dist_sales as t1Where (Select count(distinct Item_no) from dist_sales Where Dis_id = t1.Dis_id and Item_no >= t1.Item_no)<=3Order By Dis_id, Item_no, sales_qty
Go with the flow & have fun! Else fight the flow
madhivanan
Premature Yak Congratulator
22864 Posts
Posted - 2005-03-24 : 06:36:08
Nice coding MladenMadhivananFailing to plan is Planning to fail