SQL Server 2008 中的 PIVOT/UNPIVOT
我得到的子/父表如下。
MasterTable:
MasterID, Description
ChildTable
ChildID, MasterID, Description.
使用 PIVOT / UNPIVOT 如何在单行中获得如下结果。
if (MasterID : 1 有 x 子记录)
MasterID, ChildID1, Description1, ChildID2, Description2....... ChildIDx, Descriptionx
谢谢
I got child / parent tables as below.
MasterTable:
MasterID, Description
ChildTable
ChildID, MasterID, Description.
Using PIVOT / UNPIVOT how can i get result as below in single row.
if (MasterID : 1 got x child records)
MasterID, ChildID1, Description1, ChildID2, Description2....... ChildIDx, Descriptionx
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个 T_SQL,假设:
DECLARE
@MaxCountOfChild int
编辑:结果是这样的:
here is a T_SQL, assuming this:
DECLARE
@MaxCountOfChild int
EDIT: The result is this:
这很大程度上取决于交叉表列的数量是否固定。如果是,那么您可以简单地执行以下操作:
还有一种使用
CASE
函数实现类似结果的方法。但是,如果您想要在运行时确定交叉表列的数量,那么在 SQL Server 内部执行此操作的唯一方法是使用一些模糊的动态 SQL。这超出了 SQL Server 提供数据(而不是信息)的主要目的范围。如果您想要动态交叉表,我建议不要在 SQL Server 中执行此操作,而是使用报告工具或在中间层组件中构建结果集。
It greatly depends on whether the number of crosstabbed columns is fixed. If they are, then you can simply do something like:
There is also a way of achieving similar results use
CASE
functions.However, if what you want is to have the number of crosstab columns determined at runtime, then the only means to do that inside of SQL Server is to use some fugly dynamic SQL. This is outside the realm of SQL Server's primary purpose which is to serve up data (as opposed to information). If you want a dynamic crosstab, I would recommend not doing it in SQL Server but instead use a reporting tool or build your result set in a middle-tier component.