如歌根据指定字段的值选取不同的字段值??

sunfly028 2007-12-12 04:48:32
表结构如下:
F1 F2 F3 F4 F5
1 2 3 4 1
5 6 7 8 2
...

当F5=1时选取F1、F3字段
当F5=2时选取F2、F4字段

请问如何实现?谢谢~
...全文
68 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
surpasslight 2007-12-12
  • 打赏
  • 举报
回复
create table tb (F1 int, F2 int, F3 int, F4 int, F5 int)
insert into tb values( 1, 2, 3, 4, 1 )
insert into tb values( 5, 6, 7, 8, 2 )

select f5 ,
f1 = case when f5 = 1 then f1 else f2 end ,
f2 = case when f5 = 2 then f4 else f3 end
from tb

drop table tb
sunfly028 2007-12-12
  • 打赏
  • 举报
回复
谢谢两位了
wzy_love_sly 2007-12-12
  • 打赏
  • 举报
回复
1 3
6 8
wzy_love_sly 2007-12-12
  • 打赏
  • 举报
回复
declare @tb table (f1 int,f2 int,f3 int,f4 int,f5 int)
insert into @tb select 1,2,3,4,1
insert into @tb select 5,6,7,8,2

select
case when f5=1 then f1 when f5=2 then f2 end as f1,
case when f5=1 then f3 when f5=2 then f4 end as f2
from @tb

dawugui 2007-12-12
  • 打赏
  • 举报
回复
--上面写错了.
create table tb (F1 int, F2 int, F3 int, F4 int, F5 int)
insert into tb values( 1, 2, 3, 4, 1 )
insert into tb values( 5, 6, 7, 8, 2 )
go

select f5 ,
f1 = case when f5 = 1 then f1 else f2 end ,
f2 = case when f5 = 2 then f4 else f3 end
from tb

drop table tb

/*
f5 f1 f2
----------- ----------- -----------
1 1 3
2 6 8

(所影响的行数为 2 行
*/
kk19840210 2007-12-12
  • 打赏
  • 举报
回复
select case f5 when 1 then f1 else f2 end,case f5 when 1 then f3 else f4 end from tab
dawugui 2007-12-12
  • 打赏
  • 举报
回复
create table tb (F1 int, F2 int, F3 int, F4 int, F5 int)
insert into tb values( 1, 2, 3, 4, 1 )
insert into tb values( 5, 6, 7, 8, 2 )
go

select f5 ,
f1 = case when f5 = 1 then f1 else f3 end ,
f2 = case when f5 = 2 then f2 else f4 end
from tb

drop table tb

/*
f5 f1 f2
----------- ----------- -----------
1 1 4
2 7 6

(所影响的行数为 2 行)
*/
dawugui 2007-12-12
  • 打赏
  • 举报
回复
select f5 , 
f1 = case when f5 = 1 then f1 else f3 end ,
f2 = case when f5 = 2 then f2 else f4 end
from tb

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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