[英]SQL Server: pivoting without aggregation on a table with two columns
这是一个测试问题。 我有一张两列的桌子。 我想对其中一个进行透视,然后输出另一个。
表结构:
(Name varchar(10), Age int)
我需要将年龄值作为列输出,并在每个年龄值下方列出“名称”。
通过搜索,我仅看到一些示例,其中至少有另外一列用于“分组依据”,以免缺少更好的用语。 换句话说,输出的每一行都有一个共同的因素。 我的问题没有此属性。
我试过了:
SELECT
[agevalue1], [agevalue2], [agevalue3], [agevalue4]
FROM
(SELECT Name, Age FROM MyClass) AS SourceTable
PIVOT
(MAX(Name)
FOR Age IN ([agevalue1], [agevalue2], [agevalue3], [agevalue4])
) AS PivotTable;
我将agevalue *指定为字符串,即用引号引起来。 我的列标题没问题,但它们下面有一排NULL。
PS:该解决方案不需要使用数据透视,但是我想不出另一种方法。
样本数据:
Name Age
Bob 11
Rick 25
Nina 30
Sam 11
Cora 16
Rachel 25
所需的输出:
11 16 25 30
Bob Cora Rick Nina
Sam NULL Rachel NULL
尝试这个 :
with tab as
(
Select 'A' Name, 10 Age union all
Select 'B',11 union all
Select 'c',10 union all
Select 'D',11 union all
Select 'E',11 union all
Select 'F',11
)
select distinct
Age
, stuff((
select ',' + g.Name
from tab g
where g.age = g1.age
order by g.age
for xml path('')
),1,1,'') as Names_With_Same_Age
from tab g1
group by g1.age,Name
要将它们分组在一起:
11 16 25 30
Bob Cora Rick Nina
并将它们与另一组分开,例如:
11 16 25 30
Sam NULL Rachel NULL
它们之间的每一行之间必须有所不同,因为执行MAX(Name)
将为每个Age仅获得一个Name。
该查询创建一个数字,该数字将特定的Age
链接到行号,然后透视结果。 如您所说, PIVOT
将按PIVOT
函数中未引用的所有列进行分组,因此它将按此行索引器进行分组,从而按需要分隔值。
;WITH IndexedClass AS
(
SELECT
M.Name,
M.Age,
-- The ordering will determine which person goes first for each Age
RowIndexer = ROW_NUMBER() OVER (PARTITION BY M.Age ORDER BY M.Name)
FROM
MyClass AS M
)
SELECT
P.[11],
P.[16],
P.[25],
P.[30]
FROM
IndexedClass AS I
PIVOT (
MAX(I.Name) FOR I.Age IN ([11], [16], [25], [30])
) AS P
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.