取模问题

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
最后用取模解答这个问题,以前有见过人用取模解答的,现在找不到了
...全文
128 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
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
*/

22,302

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧