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.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Complex Query

Author  Topic 

scelamko
Constraint Violating Yak Guru

309 Posts

Posted - 2006-07-24 : 09:11:18
guys

I have table with 3 columns

seq area page
_____________________
1 300 0
1 200 0
1 100 0
1 400 0
2 600 0
2 500 0
2 300 0
2 700 0

I want a query for each sequence which sorts top 3 areas for each sequence. For example in the above table my result set
should be

seq area
_____________
1 400
1 300
1 200
2 700
2 600
2 500

Any suggestions/inputs on writing such query??

Thanks


khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2006-07-24 : 09:14:03
http://weblogs.sqlteam.com/mladenp/archive/2005/08/01/7421.aspx. Point No 2


KH

Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2006-07-24 : 10:37:39
Or this variant
-- Prepare test data
declare @table table (seq tinyint, area smallint, page tinyint)

insert @table
select 1, 300, 0 union all
select 1, 200, 0 union all
select 1, 100, 0 union all
select 1, 400, 0 union all
select 2, 600, 0 union all
select 2, 500, 0 union all
select 2, 300, 0 union all
select 2, 700, 0

-- Do the work (this is the code you run on your computer).
select t0.seq,
b0.i * isnull(max(t0.area), 0) +
b1.i * isnull(max(t1.area), 0) +
b2.i * isnull(max(t2.area), 0) area
from (
select seq,
max(area) area
from @table
group by seq
) t0
left join @table t1 on t1.seq = t0.seq and t1.area < t0.area
left join @table t2 on t2.seq = t1.seq and t2.area < t1.area
cross join (select 0 i union all select 1) b0
cross join (select 0 i union all select 1) b1
cross join (select 0 i union all select 1) b2
where b0.i + b1.i + b2.i = 1
group by t0.seq,
b0.i,
b1.i,
b2.i
having b0.i * isnull(max(t0.area), 0) +
b1.i * isnull(max(t1.area), 0) +
b2.i * isnull(max(t2.area), 0) > 0
order by t0.seq,
b0.i * isnull(max(t0.area), 0) +
b1.i * isnull(max(t1.area), 0) +
b2.i * isnull(max(t2.area), 0) DESC
This is the output

Seq Area
--- ----
1 400
1 300
1 200
2 700
2 600
2 500



Peter Larsson
Helsingborg, Sweden
Go to Top of Page
   

- Advertisement -