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.
| Author |
Topic |
|
sonalshastry
Starting Member
3 Posts |
Posted - 2009-12-01 : 05:10:24
|
HI, I have a bill table with following detailClient, bill_date,bill_amount, branch ...I need to fetch data for top 5 client from every branch below query gives me the data across all branchSELECT TOP 5 * FROM (Select Client_id, branch , sum(bill_amount)amountfrom dbo.billtablewhere trade_date >= '01 oct 2009' and trade_date <= '31 oct 2009'group by branch,Client_id)ORDER BY ter_branch tr DESC please help |
|
|
gangadhara.ms
Aged Yak Warrior
549 Posts |
Posted - 2009-12-01 : 05:16:00
|
| Hope this will help you..SELECT TOP 5 * FROM (Select Client_id, branch , sum(bill_amount)amountfrom dbo.billtablewhere trade_date >= '01 oct 2009' and trade_date <= '31 oct 2009'group by branch,Client_id) TempORDER BY branch,Client_id DESC |
 |
|
|
sonalshastry
Starting Member
3 Posts |
Posted - 2009-12-01 : 05:37:46
|
| thanks for reply but this change is resulting in top 5 client from single branch which start with 'A'I think more clarification in result will help you to understand the issue Expected outputClient, bill_amount, branch1 10000 abc2 9000 abc3 8000 abc4 7000 abc5 6000 abc11 10100 def12 9020 def13 8600 def14 7400 def15 6500 defawaiting reply.. |
 |
|
|
gangadhara.ms
Aged Yak Warrior
549 Posts |
Posted - 2009-12-01 : 05:55:03
|
| Hi Sonal Shastry,Here is the query for to achieve the same.SELECT TOP 5 CLIENT_ID, BRANCH , SUM(BILL_AMOUNT)AMOUNTFROM DBO.BILLTABLEWHERE TRADE_DATE >= '01 OCT 2009' AND TRADE_DATE <= '31 OCT 2009'AND BRANCH='A'--u have to hard code the branch for your need GROUP BY BRANCH,CLIENT_IDUNION SELECT TOP 5 CLIENT_ID, BRANCH , SUM(BILL_AMOUNT)AMOUNTFROM DBO.BILLTABLEWHERE TRADE_DATE >= '01 OCT 2009' AND TRADE_DATE <= '31 OCT 2009'AND BRANCH='B' --u have to hard code the branch for your need GROUP BY BRANCH,CLIENT_IDORDER BY branch,Client_id DESCLike this u can continue up to entire branch.. |
 |
|
|
sonalshastry
Starting Member
3 Posts |
Posted - 2009-12-01 : 06:14:17
|
| Hi, hard coding of branch is not feasible as there are 900 branchescan some kind of do while loop work in SQL query |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
|
|
|
|
|
|
|