Dynamic table creation in SQL Server [duplicate]

2019-07-26 18:27发布

This question already has an answer here:

I have a situation like this

+---------+-----------+------------+
| FieldNo | FieldName | Substring  |
+---------+-----------+------------+
|       1 | A         | 8          |
|       1 | A         | A          |
|       1 | A         | DC         |
|       2 | B         | 7          |
|       3 | C         | 22         |
|       3 | C         | 37         |
+---------+-----------+------------+

Need output like this:

+----+------+------+
| A  |  B   |  C   |
+----+------+------+
| 8  | 7    | 22   |
| A  | Null | 37   |
| DC | Null | Null |
+----+------+------+

Any suggestions how I can do this in SQL Server?

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

select @cols = STUFF((SELECT ',' + QUOTENAME(Field_name) 
                    from bear_crossjoin
                    group by FIELD_NAME, FIELDNUMBER
                    order by FIELDNUMBER
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = N'SELECT ' + @cols + N' from 
             (
                select substring, Field_name
                from bear_crossjoin
            ) x
            pivot 
            (
                max(substring)
                for field_name in (' + @cols + N')
            ) p '

exec sp_executesql @query

2条回答
Lonely孤独者°
2楼-- · 2019-07-26 18:56

It seems you are trying to PIVOT by row number instead of directly on the field names. The approach below pivots using the row number to get the desired output:

DECLARE @Data TABLE (FieldNo INT, FieldName VARCHAR(50), [Substring] VARCHAR(500))
INSERT @Data VALUES
    (1, 'A', '8'),
    (1, 'A', 'A'),
    (1, 'A', 'DC'),
    (2, 'B', '7'),
    (3, 'C', '22'),
    (3, 'C', '37')

;WITH DataRows AS (
    SELECT
        FieldName,
        [Substring],
        ROW_NUMBER() OVER (PARTITION BY FieldNo ORDER BY FieldName, [Substring]) AS RowNum
    FROM @Data
)
    SELECT
        CONVERT(VARCHAR(10), [A]) AS [A],
        CONVERT(VARCHAR(10), [B]) AS [B],
        CONVERT(VARCHAR(10), [C]) AS [C]
    FROM DataRows
        PIVOT (MAX([Substring]) FOR FieldName IN ([A], [B], [C])) T

This yields the desired output:

A          B          C
---------- ---------- ----------
8          7          22
A          NULL       37
DC         NULL       NULL
查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-26 18:58

I've assumed the table name as tblTemp. Try this

DECLARE @colList NVARCHAR(max)
DECLARE @query NVARCHAR(max)

select @colList = coalesce(@colList + ',', '') +  convert(varchar(12),TT.FIELDNAME)
from (SELECT DISTINCT FIELDNAME FROM tblTemp) TT
order by TT.FIELDNAME


SET @query = 'SELECT ' + @colList + ' FROM
(
SELECT row_number() over(partition by FIELDNO
                        order by FIELDNO) seq,
       FieldName, [Substring]
FROM tblTemp ) als
PIVOT
( MAX([SUBSTRING])
  FOR FieldName IN (' + @colList + ')
) piv'

exec sp_executesql @query

fiddle

查看更多
登录 后发表回答