请问这条SQL语句应该怎么写?

s_hluo 2007-01-30 02:25:44
现有一个表, 结构和数据如下:

A B C
1 2 S1
1 2 S3
1 2 S2

其中A和B列为数字类型, C为字符串类型, 且C列的值只有S1,S2,S3三个, A列的值只为1, B列的值只为2, 现在我想把表的结构调整一下, 显示如下:
A B C1 C2 C3
1 2 S1 S2 S3

请问这条SQL语句应该怎么写? 谢谢.
...全文
290 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
s_hluo 2007-01-30
  • 打赏
  • 举报
回复
谢谢各位. 结贴.
believe209 2007-01-30
  • 打赏
  • 举报
回复
mark!
收藏!
s_hluo 2007-01-30
  • 打赏
  • 举报
回复
To: marco08(天道酬勤)

谢谢你耐心的解答, :)

如果C列有3至10个值的话, 写起来是不是会比较麻烦?
w75251455 2007-01-30
  • 打赏
  • 举报
回复
TO:marco08(天道酬勤) ( )
别人都说了里面不只有三个~~还不一定有几个~~你搞什么飞机啊
marco08 2007-01-30
  • 打赏
  • 举报
回复
create table T(A int, B int, C varchar(10))
insert T select 1, 2, 'H'
union all select 1, 2, 'J'
union all select 1, 2, 'K'

select A, B,
C1=(select min(C) from T where A=tmp.A and B=tmp.B),
C2=(select top 1 C from T where A=tmp.A and B=tmp.B and C not in(
select min(C) from T where A=tmp.A and B=tmp.B union all select max(C) from T where A=tmp.A and B=tmp.B
)),
C3=(select max(C) from T where A=tmp.A and B=tmp.B)
from T as tmp
group by A, B

--result
A B C1 C2 C3
----------- ----------- ---------- ---------- ----------
1 2 H J K

(1 row(s) affected)
w75251455 2007-01-30
  • 打赏
  • 举报
回复
to:不知道能不能实现?
反正我不会....
s_hluo 2007-01-30
  • 打赏
  • 举报
回复
to: w75251455(砍破)
我看懂了你的意思, :), 谢谢.

不过现在我想用一条SQL语句实现, 不想动态执行SQL语句.

不知道能不能实现?
s_hluo 2007-01-30
  • 打赏
  • 举报
回复
c1, c2, c3的值相当于传参数进去.
zsl5305256 2007-01-30
  • 打赏
  • 举报
回复
那也要有个规律;
如c1,c2,c3分别要与那些值对应!
w75251455 2007-01-30
  • 打赏
  • 举报
回复
问这种题~应该是40分以上的!
w75251455 2007-01-30
  • 打赏
  • 举报
回复
create table T(A int, B int, C varchar(10))
insert T select 1, 2, 'S1'
union all select 1, 2, 'S3'
union all select 1, 2, 'S2'

insert into t values(2,3,'s1')
insert into t values(2,2,'s2')


declare @table varchar(5000)
set @table = 'select a,b,'
select @table=@table+'(select c from t bb where bb.c='+QUOTENAME(c,'''')+
' and bb.a=aa.a and bb.b=aa.b)'+QUOTENAME(c)+','
from t group by c
set @table = left(@table,len(@table)-1)+'from t aa group by a,b'
exec (@table)
s_hluo 2007-01-30
  • 打赏
  • 举报
回复
如果C列的值是只有三个, 但是不确定是什么值的话怎么办?
比如C列的值可能是: H,J,K 也可能是U,M ,L ...
请问该怎么写?
marco08 2007-01-30
  • 打赏
  • 举报
回复
create table T(A int, B int, C varchar(10))
insert T select 1, 2, 'S1'
union all select 1, 2, 'S3'
union all select 1, 2, 'S2'

select A, B,
C1=max(case when C='S1' then C end),
C2=max(case when C='S2' then C end),
C3=max(case when C='S3' then C end)
from T
group by A, B

--result
A B C1 C2 C3
----------- ----------- ---------- ---------- ----------
1 2 S1 S2 S3

(1 row(s) affected)
marco08 2007-01-30
  • 打赏
  • 举报
回复
select A, B,
C1=max(case when C='S1' then C end),
C2=max(case when C='S2' then C end),
C3=max(case when C='S3' then C end)
from T
group by A, B

34,588

社区成员

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

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