| Author |
Topic |
|
hello101
Starting Member
1 Post |
Posted - 2011-04-20 : 02:14:00
|
| Hi Everyone,My question is as follows.Companycompany-names Salesatt 500verizon 100sprint 400cox 200comcast 600tmobile 800apple 850Above is a table Company with 2 columns.I want to know the nearest competitor of cox which is one competitor above cox(which is sprint) and one competitor below cox(verizon).The competition is based on the sales number so therefore the result should display the sales and company name if sprint, cox and verizon.I have used rank.select company-name,sales, rank() over(sales)as RANK from companyIf I execute the query above than I will get the rank of all the company in a column RANK but I want only one above and one below competitor of cox.Hope you understood.Thank you. |
|
|
raghuveer125
Constraint Violating Yak Guru
285 Posts |
Posted - 2011-04-20 : 02:51:07
|
| Hey you are using oracle?Raghu' S |
 |
|
|
lionofdezert
Aged Yak Warrior
885 Posts |
|
|
hello110
Starting Member
3 Posts |
Posted - 2011-04-20 : 10:43:38
|
| Hi,I am using SQL server but if you know the answer in Oracle that will be helpful too.Thank you. |
 |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2011-04-20 : 10:58:55
|
| declare @company table (Co varchar(10),Sales int)INSERT INTO @CompanySELECT 'att', 500 UNION ALLSELECT 'verizon', 100 UNION ALLSELECT 'sprint', 400 UNION ALLSELECT 'cox', 200 UNION ALLSELECT 'comcast', 600 UNION ALLSELECT 'tmobile', 800 UNION ALLSELECT 'apple', 850 ;with cteas( select co,sales,rank() over(order by sales) as rownfrom @company) select * from ctewhere rown >= (select rown-1 from cte where co = 'cox')and rown <= (select rown+1 from cte where co = 'cox') JimEveryday I learn something that somebody else already knew |
 |
|
|
hello110
Starting Member
3 Posts |
Posted - 2011-04-20 : 12:07:12
|
| Thank you Jimf,Is cte like a temporary table which consist the result select co,sales,rank() over(order by sales) as rownfrom @companycan we give another name instead of cte? No right since it is common table expressions |
 |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2011-04-20 : 12:15:49
|
| Correct, it is a Common Table Expression, which is like a temporary table -- it goes away after the transaction completes. You can name the cte anythng you want, e.g.;with RankedSalesas(select co,sales,rank() over(order by sales) as rownfrom @company)select * from RankedSalesJimEveryday I learn something that somebody else already knew |
 |
|
|
hello110
Starting Member
3 Posts |
Posted - 2011-04-20 : 12:43:38
|
| Got it. Thank you so much...Appreciate it. |
 |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2011-04-20 : 12:46:23
|
| You're Welcome!JimEveryday I learn something that somebody else already knew |
 |
|
|
|