取模问题

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及数量的,数量只显示一次,结果如下
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
最后用取模解答这个问题,以前有见过人用取模解答的,现在找不到了
...全文
61 点赞 收藏 3
写回复
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
回复
幸运的意外 2010-10-20
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
*/
回复
相关推荐
发帖
疑难问题
创建于2007-09-28

2.1w+

社区成员

MS-SQL Server 疑难问题
申请成为版主
帖子事件
创建了帖子
2010-10-19 10:43
社区公告
暂无公告