问题描述
我有以下数据集
我希望输出如下:
问题还在于我有一个不固定数量的 Accounts &不固定数量的联系人
The problem is also that I have an unfixed amount of Accounts & unfixed amount of Contacts
推荐答案
如果您要应用 PIVOT
函数,您将需要使用聚合函数来获得结果,但您也将想使用像 row_number()
这样的窗口函数来为帐户中的每个联系人生成唯一的序列.
If you are going to apply the PIVOT
function, you will need to use an aggregate function to get the result but you will also want to use a windowing function like row_number()
to generate a unique sequence for each contact in the account.
首先,您将查询类似于以下内容的数据:
First, you will query your data similar to:
参见SQL Fiddle with Demo.这将创建一个具有唯一序列的新列:
See SQL Fiddle with Demo. This will create a new column with the unique sequence:
如果您的列数有限,那么您可以对查询进行硬编码:
If you have a limited number of columns, then you could hard-code your query:
参见SQL Fiddle with Demo
如果您有未知数量的列,那么您将不得不使用动态 SQL:
If you have an unknown number of columns, then you will have to use dynamic SQL:
参见SQL Fiddle with Demo.两者都会给你一个结果:
See SQL Fiddle with Demo. Both will give you a result of:
这篇关于转置没有聚合的行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!