gpt4 book ai didi

sql - 连接两个表然后将一个表中的行转置为列名

转载 作者:行者123 更新时间:2023-12-04 04:23:36 24 4
gpt4 key购买 nike

我正在尝试连接两个表

ColumnNames
ID |Name |Type |Status |
-----------------------------------------------------
1 |Fullname |varchar |Active
2 |Email |varchar |Active
3 |Position |varchar |Active
4 |Category |varchar |Active
ColumnValues
ID |ColumnNameID |value |Status |
-----------------------------------------------------
1 |1 |Linda |Active
2 |2 |linda@email.com |Active
3 |3 |Soft Eng. |Active
4 |4 |Cat 1 |Active
5 |1 |Remil |Active
6 |2 |Remil@email.com |Active
7 |3 |Senior Soft Eng. |Active
8 |4 |Cat 2 |Active
9 |1 |Ash |Active
10 |2 |ash@email.com |Active
11 |3 |Soft Eng. |Active
12 |4 |Cat 1 |Active

然后将数据行(来自 ColumnNames 表上的名称)转换为列名。

现在,我被告知要使用 Pivot。我已经成功地使用 pivot 转置单个表中的行,但我对如何转置连接表中的行感到困惑。

下面是我试过的代码,但它给我一个错误,说列不存在

    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(ColumnName)
from tm.ColumnName
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')

set @query = 'SELECT ColumnNameID, ' + @cols + ' from
(
select i.ColumnNameID, i.ColumnValue
from tm.ColumnValue i
inner join tm.ColumnName a
on i.ColumnNameID = a.ColumnNameID
) x
pivot
(
max(ColumnNameID)
for ColumnValue in (' + @cols + ')
) p '

execute(@query)

预期结果应该是

Fullname  |Email                 |Position             |Category |
--------------------------------------------------------------------
Linda |linda@email.com |Soft Eng. |Cat 1
Remil |Remil@email.com |Senior Soft Eng. |Cat 2
Ash |ash@email.com |Soft Eng. |Cat 1

我在这种情况下是否正确使用了 pivot?

最佳答案

考虑在 INNER JOIN 中包含每个列值类型(全名、电子邮件、职位、类别)的 ROW_NUMBER 排名,然后通过 PIVOT 运行。无需动态构建 SQL:

SELECT [Fullname], [Email], [Position], [Category]
FROM (
SELECT i.ColumnValue, a.[Name],
ROW_NUMBER() OVER (PARTITION BY a.[Name] ORDER BY a.ColumnNameID) AS rn
FROM ColumnValues i
INNER JOIN ColumnNames a
ON i.ColumnNameID = a.ColumnNameID
) tbl

PIVOT
(MAX(ColumnValue)
FOR [Name] IN ([Fullname], [Email], [Position], [Category])
) pvt
ORDER BY rn

Rextester demo

对于动态查询,构建一个@cols 字符串以放置在数据透视查询的特定位置。

DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.[Name])
FROM ColumnNames c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')

SET @query = 'SELECT ' + @cols + '
FROM (
SELECT i.ColumnValue, a.[Name],
ROW_NUMBER() OVER (PARTITION BY a.[Name] ORDER BY a.ColumnNameID) AS rn
FROM ColumnValues i
INNER JOIN ColumnNames a
ON i.ColumnNameID = a.ColumnNameID
) tbl

PIVOT
(MAX(ColumnValue)
FOR [Name] IN (' + @cols + ')
) pvt
ORDER BY rn'

EXECUTE(@query)

Rextester demo

关于sql - 连接两个表然后将一个表中的行转置为列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58458617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com