sql语句:有关判断字段中单双数的问题

csuxp2008 2009-08-27 05:50:10
表test

id
1
2
3
4
5
6
7
8
9
10

需要得到如下的结果:
单数 双数
1 2
3 4
5 6
7 8
9 10

我写的sql语句如下:
select
case when mod(id,2)=1 then id end 单数,
case when mod(id,2)=0 then id end 双数
from test;

单数 双数
---------- ----------
1
2
3
4
5
6
7
8
9
10

我想问下null行是怎么产生的,如何才能得到我要的结果?


...全文
876 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
csuxp2008 2009-08-27
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 wildwave 的回复:]
不,不一定单数多还是双数多呢,你怎么确定那边是左
[/Quote]

恩,确实!
蜜_Lumia 2009-08-27
  • 打赏
  • 举报
回复
我也来拍一下
小灰狼W 2009-08-27
  • 打赏
  • 举报
回复
不,不一定单数多还是双数多呢,你怎么确定那边是左
csuxp2008 2009-08-27
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 wildwave 的回复:]
还有就是表连接了
SQL codeselect a.单数,b.双数from
(select id 单数,rownum rnfrom testwhere mod(id,2)=1)afulljoin
(select id 双数,rownum rnfrom testwhere mod(id,2)=0)bon a.rn=b.rn
[/Quote]

这个不错,我觉得使用left join更明了一些
小灰狼W 2009-08-27
  • 打赏
  • 举报
回复
又来拍我马屁..
呦呦 2009-08-27
  • 打赏
  • 举报
回复
嘿嘿,高手就是高手!
小灰狼W 2009-08-27
  • 打赏
  • 举报
回复
根据需要order 一下
小灰狼W 2009-08-27
  • 打赏
  • 举报
回复
还有就是表连接了
select a.单数,b.双数 from
(select id 单数,rownum rn from test where mod(id,2)=1)a
full join
(select id 双数,rownum rn from test where mod(id,2)=0)b
on a.rn=b.rn
csuxp2008 2009-08-27
  • 打赏
  • 举报
回复
不知道还有没有更简单的方法来实现,等待
小灰狼W 2009-08-27
  • 打赏
  • 举报
回复
你的case里,满足条件的输出id,else 没写,则默认为null
这就是空值的来历
csuxp2008 2009-08-27
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wildwave 的回复:]
SQL codeselectmax(单数)单数,max(双数)双数from(selectcasewhen mod(id,2)=1then idend 单数,casewhen mod(id,2)=0then idend 双数,
row_number(partitionby mod(id,2)orderby id)rnfrom test
)groupby rnorderby rn
[/Quote]

你写错了,row_number() over()
根据你的方法,我要的效果达到了,不过我还是想知道为什么我写的sql语句会出现null的数据,可否帮忙解释下
小灰狼W 2009-08-27
  • 打赏
  • 举报
回复
。。打错了
select max(单数)单数,max(双数)双数 from(    
select
case when mod(id,2)=1 then id end 单数,
case when mod(id,2)=0 then id end 双数,
row_number(partition by mod(id,2) order by id)rn
from test
)
group by rn
order by rn
小灰狼W 2009-08-27
  • 打赏
  • 举报
回复
没有聚合,查询前后的记录数当然是一样多的
经过case
产生空值
小灰狼W 2009-08-27
  • 打赏
  • 举报
回复
select max(单数)单数,max(双数)双数 from(    
select
case when mod(id,2)=1 then id end 单数,
case when mod(id,2)=0 then id end 双数,
row_number(partition by mod(id,2) order by id)rn
from test
)
group by rn
order by rn

17,086

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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