如何将水平行转换为垂直行

时间:2016-04-07 01:43:25

标签: sql sql-server tsql pivot

我有一个动态查询,它在sql

中获取62列的行

查询就像这样

DECLARE @SQLQuery AS nvarchar(max)

DECLARE @columns nvarchar(max)

SELECT
  @columns = ISNULL(@columns + ', ', '') + QUOTENAME(Column_name)
FROM (SELECT
  Column_name
FROM
 (SELECT
  Column_name,
  ROW_NUMBER() OVER (PARTITION BY Column_name ORDER BY Column_name) AS Rows
FROM information_Schema.Columns

WHERE Table_Name IN ('Parking', 'AIV_Parking')
AND column_name NOT IN ('IssueNo', 'Issuedate', 'Agency', 'OfficerName', 'OfficerId', 'Beat', 'UNITSERIAL', 'VEHLICNO', 'VEHLICSTATE', 'VEHLICEXPDATE', 'VEHLICTYPE', 'VEHMAKE',
'VEHMODEL', 'VEHBODYSTYLE', 'VEHVIN4', 'VEHVIN', 'ISSUENOCHKDGT', 'VEHCOLOR1', 'VEHCOLOR2', 'PERMITNO', 'VEHLABELNO', 'LOCBLOCK', 'LOCSTREET', 'LOCDESCRIPTOR', 'LOCTRAVELDIR', 'LOCSIDEOFSTREET',
'LOCSUBURB', 'LOCLOT', 'LOCCROSSSTREET1', 'LOCCROSSSTREET2', 'LOCSTATE', 'LOCPOSTALCODE', 'METERNO', 'METERBAYNO', 'REMARK1', 'REMARK2')) p
WHERE Rows = 2) RequiredColumns

EXEC ('SELECT ' + @columns + '  FROM AIV_Parking Where  Issueno =''100000600''')

这给了我以下记录

结果是下面的东西,我一次只能得到一行。

|ACTLINE1  |    ACTLINE2 |   AUTOPROC_UNIQUEKEY |   COURTADDR|  IssueNo|.......

 |SUBIACO  |   LOCAL LAWS|       NULL            |      NULL |    123 |

现在我希望将其转换为:

|FieldName       |                                    FieldValue

|ACTLINE1        |                                      SUBIACO  

|ACTLINE2        |                                      LOCAL LAWS 

|ISSUENO         |                                      123

在旋转这些列时,我只想要那些有价值的列我不想要那些值为null或者为' '

1 个答案:

答案 0 :(得分:0)

您需要使用UNION ALL并使用WHERE子句过滤结果:

DECLARE @SQLQuery AS NVARCHAR(MAX) = ''

SELECT @SQLQuery = @SQLQuery +
'SELECT ''' + COLUMN_NAME + ''' AS FieldName, CAST(' + QUOTENAME(COLUMN_NAME)  + ' AS NVARCHAR(MAX)) AS FieldValue 
FROM AIV_Parking 
WHERE Issueno =''100000600'' 
UNION ALL' + CHAR(10)
--QUERY HERE TO GET COLUMNS FROM INFORMATION_SCHEMA.COLUMNS
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME IN('Parking','AIV_Parking')

IF @SQLQuery <> '' BEGIN
    -- Remove the last occurence of UNION ALL
    SELECT @SQLQuery = LEFT(@SQLQuery, LEN(@SQLQuery) - 11)

    SELECT @SQLQuery = 
    'SELECT * FROM (' + @SQLQuery + ') t WHERE FieldValue IS NOT NULL AND FieldValue <> '''''

    EXEC(@SQLQuery)
END

请注意,您需要CAST FieldValue NVARCHAR(MAX)UNION或任何不会产生转换错误的数据类型。这是因为当使用stage.example.com时,所有列必须具有相同的数据类型,否则,它们将转换为具有更高数据类型优先级的列。