sql - 多对多成一排
问题描述
我在 SQL Server 2008 R2 中有一个类似于下面的“表”的视图。
我想要一个“交叉表”视图或存储过程来获得如下所述的结果。该视图由三个表 Main --- to many Props --- to many lineitem
Mainname | Prop | lineitems
---------+------+------------
Smith | P1 | cheese
Smith | P1 | tires
Smith | P1 | baseballs
Smith | P2 | gel
Smith | P3 | windows
Smith | P3 | guitar
Jones | T4 | shoes
Lane | Q1 | cushion
Lane | Q2 | dirt
我需要让它看起来像这样:
Mainname | Prop1 | lineitems1 | lineitems2 | lineitems3 | Prop2 | lineitems1 | Prop3 | lineitems1 | lineitems2
---------+-------+------------+------------+------------+-------+------------+-------+------------+-----------
Smith | P1 | cheese | tires | baseballs | P2 | gel | P3 | windows | guitar
Jones | T4 | shoes
Lane | P5 | cushion | <null> | <null> | P6 | dirt
解决方案
虽然拉努的回答可能有效(我没有尝试过)。对我有用的解决方案是这样的。我在表格中添加了另一列...成本
declare @Count int,@Cur int
declare @Qry nvarchar(4000)
set @Cur=1
select @Count=max(t.count) from (
select proposal, count(lineitems) count from view_1 group by proposal) t
set @Qry=''
while @Cur<@Count+1
begin
set @Qry= @Qry + ',(select t.lineitems from (select ROW_NUMBER() over(order by lineitems) ROW_NUMBER,
lineitems from view_1 where proposal = t1.proposal) t where ROW_NUMBER='+ cast(@Cur as varchar(10)) + ') as lineitem' + cast(@Cur as varchar(10))
set @Qry= @Qry + ',(select t.costs from (select ROW_NUMBER() over(order by lineitems) ROW_NUMBER,
costs from view_1 where proposal = t1.proposal) t where ROW_NUMBER='+ cast(@Cur as varchar(10)) + ') as costs' + cast(@Cur as varchar(10))
set @Cur=@Cur+1
end
set @Qry='select distinct t1.grantname, t1.proposal ' + @Qry + ' from view_1 t1 order by 1, 2'
print @Qry
exec sp_executesql @Qry
推荐阅读
- reactjs - 在反应js中显示选定日期的数据
- c++ - 具有特定数组维度的模板类
- wordpress - 通过根目录访问 wp 插件脚本文件
- ios - Flutter:带有约束的灵活项目行
- apache-spark - Pyspark 使用 kafka 读取现有记录
- reactjs - 在打字稿反应中获取对象可能是“未定义的”
- amazon-web-services - 弹性搜索:从远程 aws vpc 主机重新索引时忽略 ssl
- c# - 如何计算 JSON 文件中的对象
- circleci - 使用以下命令安装节点和 npm 时,CircleCI 构建失败。任何人都可以对此有所了解吗?
- next.js - NextJS 项目编译因 JSEncrypt 失败