一个转二维表的查询问题!在线等!

无风飞尘 2004-11-22 01:42:00
表A:

ID CountryID Country

.. 001 美国
.. 002 日本
.. 003 德国
.. 004 法国
.. 005 中国
.. 008 意大利

表C:
ID X Y CountryID

.. 1 1 005
.. 2 1 002
.. 3 1 003
.. 1 2 004
.. 2 2 001
.. 3 2 008

查询显示为:

Country1 Country2 Country3

中国 日本 德国
法国 美国 意大利

表C的X,Y是指显示的列与行,如 004 是在 第1列(X=1) 第2行(Y=2) 004表示法国(从表A得到)
...全文
108 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
pbsql 2004-11-22
  • 打赏
  • 举报
回复
上面的语句即使中间一列缺记录也无所谓
zjcxc 元老 2004-11-22
  • 打赏
  • 举报
回复
--测试

--测试数据
create table 表A(CountryID varchar(10),Country varchar(10))
insert 表A select '001','美国'
union all select '002','日本'
union all select '003','德国'
union all select '004','法国'
union all select '005','中国'
union all select '008','意大利'

create table 表C(X int,Y int,CountryID varchar(10))
insert 表C select 1,1,'005'
union all select 2,1,'002'
union all select 3,1,'003'
union all select 1,2,'004'
union all select 2,2,'001'
union all select 3,2,'008'
go

--查询处理
declare @s varchar(8000)
select @s=''
select @s=@s+',[Country'+rtrim(X)+']=max(case c.X when '+rtrim(X)+' then a.Country else '''' end)'
from 表C group by X
set @s=stuff(@s,1,1,'')
exec('
select '+@s+'
from 表A a,表C c
where a.CountryID=c.CountryID
group by Y')
go

--删除测试
drop table 表A,表C

/*--测试结果

Country1 Country2 Country3
---------- ---------- ----------
中国 日本 德国
法国 美国 意大利
--*/
pbsql 2004-11-22
  • 打赏
  • 举报
回复
select Country1=case when (id-1)%3=0 then Country else '' end,
Country2=case when (id-1)%3=1 then Country else '' end,
Country3=case when (id-1)%3=2 then Country else '' end
from
(select top 100 percent a.Country,id=(c.y-1)*3+c.x from a,c
where a.CountryID=c.CountryID order by c.y,c.x) t
group by (id-1)/3
--3表示列数,有多少列就改成多少
无风飞尘 2004-11-22
  • 打赏
  • 举报
回复
如果我的列数不定怎么写?
zjcxc 元老 2004-11-22
  • 打赏
  • 举报
回复
declare @s varchar(8000)
select @s=''
select @s=@s+',[Country'+rtrim(X)+']=max(case c.X when '+rtrim(X)+' then a.Country else '''' end)'
from 表C group by X
set @s=stuff(@s,1,1,'')
exec('
select '+@s+'
from 表A a,表C c
where a.CountryID=c.CountryID
group by Y')
lsxaa 2004-11-22
  • 打赏
  • 举报
回复
select y,
Max( case X when 1 then a.country else '' end) as Country1,
Max( case X when 2 then a.country else '' end) as Country2,
Max( case X when 3 then a.country else '' end) as Country3
from C inner join A on c.CountryID=a.CountryID
group by c.y
无风飞尘 2004-11-22
  • 打赏
  • 举报
回复
所用环境是SQL Server.

34,576

社区成员

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

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