SQL Server SQL透视- nvarchar值

zi8p0yeb  于 2022-11-21  发布在  其他
关注(0)|答案(1)|浏览(172)

我想透视我的数据,但我可以有一个聚合函数:(

SELECT [IdTask]
      ,[Name]
      ,[LogType]
      ,[Fr]
      ,[Input]
      ,[CreatedAt]
  FROM [dbo].[vRapport]

我想有这样一个结果:

有人有办法这样做吗?
谢谢
尝试使用Pivot,但没有sum()count()就不起作用

kxe2p93d

kxe2p93d1#

您可以使用ROW_NUMBER()来取得1到10的数字清单。
然后,您可以将MIN()MAX()用于nvarchar列。

SELECT [IdTask]
    , [Name]
    , [1]
    , [2]
    , [3]
    , [4]
    , [5]
    , [6]
    , [7]
    , [8]
    , [9]
    , [10]
FROM
(
SELECT [IdTask]
    , ROW_NUMBER() OVER (PARTITION BY [Name] ORDER BY [CreatedAt]) AS RowNum
    , [Name]
    , [Fr]
FROM [dbo].[vRapport]
) AS SourceTable
PIVOT
(
    MIN(Fr)
    FOR RowNum IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10])
) AS PivotTable;

如果您希望从您提供的查询开始,您可以使用CTE:

WITH CTE AS (
SELECT [IdTask]
      ,[Name]
      ,[LogType]
      ,[Fr]
      ,[Input]
      ,[CreatedAt]
  FROM [dbo].[vRapport]
)
SELECT [IdTask]
    , [Name]
    , [1]
    , [2]
    , [3]
    , [4]
    , [5]
    , [6]
    , [7]
    , [8]
    , [9]
    , [10]
FROM
(
SELECT [IdTask]
    , ROW_NUMBER() OVER (PARTITION BY [Name] ORDER BY [CreatedAt]) AS RowNum
    , [Name]
    , [Fr]
FROM CTE
) AS SourceTable
PIVOT
(
    MIN(Fr)
    FOR RowNum IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10])
) AS PivotTable;

有关ROW_NUMBER()的更多信息,请访问:https://learn.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql?view=sql-server-ver16

相关问题