这个sql语句简单

maskedman 2004-04-28 03:53:22
A表 (5个一组)
AF1 AF2 AF3
------------------
R1 1 1.1
R1 2 1.0
R1 3 1.2
R1 4 1.0
R1 5 1.0
R2 1 1.4
R2 2 1.3
R2 3 1.2
R2 4 1.0
R2 5 1.1
....
怎么生成这个表
B表
ID R1 R2
-----------------
1 1.1 1.4
2 1.0 1.3
3 1.2 1.2
4 1.0 1.0
5 1.0 1.1
...全文
82 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 元老 2004-04-29
  • 打赏
  • 举报
回复
如果组数不固定,只能用动态的,你不喜欢也没办法.

如果AF#是字符型,你可以将sum改为max,0改为''
declare @s varchar(8000)
set @s=''
select @s=@s+',['+AF1+']=max(case AF1 when '''+AF1+''' then AF3 else '''' end)'
from A表
group by AF1
exec('select id'+@s+' from A表 group by id')
maskedman 2004-04-29
  • 打赏
  • 举报
回复
邹建老大,两个都不行!!!!!!!!!!!!!!!!

第一种方法
select a.id,R1=a.AF3,R2=b.AF3 --你凭什么取a.id,
--我肯定要返回组数最多的那一种,假如R1有四组,
--R2有五组,我就要用b.id我根本不知道哪个行数最
from A表 a join A表 b on a.AF2=b.AF2
where a.AF1='R1' and b.AF1='R2'


第二种方法,假如我的AF3是字符型,并且是象'fff', 'ddd'这样的,无能为力了,
并且@s varchar(8000),我不喜欢,很大隐患,完全有可能超过8000
declare @s varchar(8000)
set @s=''
select @s=@s+',['+AF1+']=sum(case AF1 when '''+AF1+''' then AF3 else 0 end)'
from A表
group by AF1
exec('select id'+@s+' from A表 group by id')


zjcxc 元老 2004-04-28
  • 打赏
  • 举报
回复
--如果AF1的值是不固定的,就用动态SQL语句
declare @s varchar(8000)
set @s=''
select @s=@s+',['+AF1+']=sum(case AF1 when '''+AF1+''' then AF3 else 0 end)'
from A表
group by AF1
exec('select id'+@s+' from A表 group by id')
zjcxc 元老 2004-04-28
  • 打赏
  • 举报
回复
--不是理解错了,是写错表名了,两个都是A表

select a.id,R1=a.AF3,R2=b.AF3
into B表 --如果直接查询,就不加此句
from A表 a join A表 b on a.AF2=b.AF2
where a.AF1='R1' and b.AF1='R2'
internetcsdn 2004-04-28
  • 打赏
  • 举报
回复
create table t1(af1 varchar(10),af2 int,af3 float)
insert t1
select 'r1',1,1.1
union all select 'r1',2,1.2
union all select 'r2',1,1.3
union all select 'r2',2,1.4
drop table t1

--select * from t1
select * into b from(select af2,sum(case af1 when 'r1' then af3 else 0 end) as r1,
sum(case af1 when 'r2' then af3 else 0 end) as r2
from t1
group by af2)a
maskedman 2004-04-28
  • 打赏
  • 举报
回复
楼上理解错了,现在B表还不存在,要通过A表生成B表
internetcsdn 2004-04-28
  • 打赏
  • 举报
回复
联机帮助-交叉数据报表-确定
zjcxc 元老 2004-04-28
  • 打赏
  • 举报
回复

select a.id,R1=a.AF3,R2=b.AF3
from A表 a join B表 b on a.AF2=b.AF2
where a.AF1='R1' and b.AF1='R2'
internetcsdn 2004-04-28
  • 打赏
  • 举报
回复
1

34,590

社区成员

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

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