# 取模问题

tengdacom 2010-10-19 10:43:27

ID XH NUM
1 3 100
1 3 100
1 3 100
1 4 200
1 4 200
2 3 50
2 3 50
3 5 300
3 5 300
3 5 300
3 5 300
4 1 2.5

ID XH NUM
1 3 100
1 3
1 3
1 4 200
1 4
2 3 50
2 3
3 5 300
3 5
3 5
3 5
4 1 2.5

...全文
63 3 点赞 打赏 收藏 举报

3 条回复

dawugui 2010-10-20
--sql 2005方法用row_number,如一楼.
--sql 2000得用临时表处理,如下:
``````create table tb(ID int, XH int, NUM float)
insert into tb
select 1, 3, 100 union all
select 1, 3, 100 union all
select 1, 3, 100 union all
select 1, 4, 200 union all
select 1, 4, 200 union all
select 2, 3, 50 union all
select 2, 3, 50 union all
select 3, 5, 300 union all
select 3, 5, 300 union all
select 3, 5, 300 union all
select 3, 5, 300 union all
select 4, 1, 2.5

select * , px=identity(int,1,1) into tmp from tb

--只判断id
select ID ,XH ,
NUM = (case when px = (select min(px) from tmp where id = t.id) then ltrim(num) else '' end)
from tmp t
/*
ID          XH          NUM
----------- ----------- ----------------------
1           3           100
1           3
1           3
1           4
1           4
2           3           50
2           3
3           5           300
3           5
3           5
3           5
4           1           2.5

（所影响的行数为 12 行）
*/

--同时判断id , xh
select ID ,XH ,
NUM = (case when px = (select min(px) from tmp where id = t.id and XH = t.XH) then ltrim(num) else '' end)
from tmp t
/*
ID          XH          NUM
----------- ----------- ----------------------
1           3           100
1           3
1           3
1           4
1           4
2           3           50
2           3
3           5           300
3           5
3           5
3           5
4           1           2.5

（所影响的行数为 12 行）
*/

drop table tb , tmp``````
• 打赏
• 举报

2005里处理的效率高很多呀。呵呵。二楼，三楼的大侠的思想值得学习。
• 打赏
• 举报

SQLCenter 2010-10-19
``````--> 测试数据：#
if object_id('tempdb.dbo.#') is not null drop table #
create table #(ID int, XH int, NUM float)
insert into #
select 1, 3, 100 union all
select 1, 3, 100 union all
select 1, 3, 100 union all
select 1, 4, 200 union all
select 1, 4, 200 union all
select 2, 3, 50 union all
select 2, 3, 50 union all
select 3, 5, 300 union all
select 3, 5, 300 union all
select 3, 5, 300 union all
select 3, 5, 300 union all
select 4, 1, 2.5

;with cte as
(
select row=row_number()over(partition by ID,XH order by ID), * from #
)
select ID, XH, NUM=case row when 1 then ltrim(NUM) else '' end from cte

/*
ID          XH          NUM
----------- ----------- -----------------------
1           3           100
1           3
1           3
1           4           200
1           4
2           3           50
2           3
3           5           300
3           5
3           5
3           5
4           1           2.5
*/
``````
• 打赏
• 举报

2.1w+

MS-SQL Server 疑难问题

2010-10-19 10:43