sql查询结果格式转换问题,高手帮帮忙吧

zhejiuzhenenbulai 2007-11-30 08:26:57
表1中有4列,第一列l1,第2列type int,第3列flag int 第4列info varchar
现在数据记录有如下几条:
l1 type flag info
1 4 0 ‘abcd’
1 4 1 ‘efgh’
2 4 0 ’higk‘
2 4 1 ’lmno‘

现在想得到按l1列为分组的,记录新格式如下:
l1 type info0 info1
1 4 ’abcd‘ ’efgh‘
2 4 ’higk‘ ’lmno‘

请问该增么实现呀?小弟在这里谢谢了,实在是没有分了,请多帮忙吧。
...全文
116 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
liapply 2007-11-30
  • 打赏
  • 举报
回复
不错
zhejiuzhenenbulai 2007-11-30
  • 打赏
  • 举报
回复
谢谢各位英雄,首先,1楼,2楼,3楼的朋友可能理解错了我的提问了,你们的答案稍稍有些小错误。4楼的仁兄2种方法我都测试过,比较正确,在此再次谢过。
tcxx2008 2007-11-30
  • 打赏
  • 举报
回复
到底谁对呀,你们别随便写,多测试呀
leo_lesley 2007-11-30
  • 打赏
  • 举报
回复
create table tab(l1 int, type int, flag int, info varchar(10))
insert tab
select 1 ,4 , 0 ,'abcd'
union select 1 ,4 , 1 ,'efgh'
union select 2 ,4 , 0 ,'higk'
union select 2 , 4 , 1 ,'lmno'

--静态
select l1,type, info0=max(case when flag=0 then info end),
info1=max(case when flag=1 then info end)
from tab
group by l1,type

--动态

declare @s varchar(8000)
set @s='select l1,type'

select @s=@s+',info'+rtrim(flag)+'=max(case when flag='+rtrim(flag)+'then info end)'
from tab
group by flag

set @s=@s+' from tab group by l1,type'
exec( @s)


drop table tab
中国风 2007-11-30
  • 打赏
  • 举报
回复
select distinct * from ta where flag=1----如果flag为0或者1时
中国风 2007-11-30
  • 打赏
  • 举报
回复
select * from ta t where not exists(select 1 from ta where col1=t.col1 and type=t.type and flag>t.flag)
-------
select * from ta t where flag=(select max(flag) from ta where col1=t.col1 and type=t.type)
----col1为第一列列名
leo_lesley 2007-11-30
  • 打赏
  • 举报
回复
select l1,type,info0=case when flag=0 then info end,info1=case when flag=1 then info end
from 表名
group by l1,type

34,838

社区成员

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

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