In one table I try to pick up one record in each group and do not want
to use cursor. This is a huge table with 100 millons of rows. I need
performance. How can I do this?
For example, the table like below. For each group I need pick one
record (anyone). So the result will be (1,1),(2,323) or (1,234),
(2,22)....
Any suggestion will be appreciated. Wei
group value
1 234
1 3242
1 1
2 323
2 22
2 2
M A Srinivas - 31 Jul 2008 18:01 GMT
On Jul 31, 9:47 pm, weileo...@gmail.com wrote:
> In one table I try to pick up one record in each group and do not want
> to use cursor. This is a huge table with 100 millons of rows. I need
[quoted text clipped - 13 lines]
> 2 22
> 2 2
You can do this
select group , max(value) as value
from table
group by group
Steve Kass - 31 Jul 2008 18:05 GMT
If you're using SQL Server 2005 or later, you can select these rows
from a partitioned row_number:
with Numbered as (
select
*,
row_number() over (
partition by group_num
order by group_num -- since you don't care about the order
) as rn
from yourTable
)
select
<columns you need>
from Numbered
where rn = 1
With SQL Server 2000 or earlier, you will have to decide
just which row you want for each group and can specify it
with an aggregate or not exists:
select group_num, max(value) as value
from yourTable
group by group_num
Note that in this query, if you have additional columns beyond [value],
you may not want to use max() on each one, because then the results
you obtain may not be rows of the original table. Max(value) may
come from a different row than the Max(some_other_column), for
example.
Better is something like this for 2000:
select <columns>
from yourTable
where not exists (
select * from yourTable T
where T.group_num = yourTable.group_num
and T.primaryKey > yourTable.primaryKey
)
Steve Kass
Drew University
http://www.stevekass.com
>In one table I try to pick up one record in each group and do not want
>to use cursor. This is a huge table with 100 millons of rows. I need
[quoted text clipped - 14 lines]
>2 2
>
weileogao@gmail.com - 31 Jul 2008 18:45 GMT
> If you're using SQL Server 2005 or later, you can select these rows
> from a partitioned row_number:
[quoted text clipped - 60 lines]
>
> - Show quoted text -
Thanks, That is very useful.
I do have lots of columns not one. And I tried 2005 solution. It works
as I expect. Thanks again.
Wei