如何将列值转换为多个列?

时间:2019-07-23 13:56:30

标签: sql sql-server ssms

我正在尝试将一列的值转换为多列。这是下面AX表中的示例:

AAAREFNUMVALUE  AAATRANSPORTTABLE   AAAREFNUMTYPE
5000130742      5637146247              2
01832007        5637146247              3
14252108        5637146247              1
NS              5637146247              8
5000131013      5637146248              2
01829347        5637146248              3
11910275        5637146248              1
NS              5637146248              8

下面是我需要使用SQL的excel报告的最终结果。它在同一行上具有所有相关字段。 AAATRANSPORTTABLE字段与值相关,AAAREFNUMTYPE是我希望新列的排列方式:

Alpha Pro Number     Shippers BL #          PO Number     Shippers Number
11910275          SA03261264             01829347        NS
14252108          SA03256804             01832007        NS

我试图使用多个SELECT语句只是将数据过滤掉,但是出现以下错误:

  

子查询返回了多个值。当   子查询遵循=,!=,<,<=,>,> =,或当子查询用作   表达式。

尽管我很难想象如何解决此问题,但我已经考虑了PIVOT和MERGE函数。我提供的数据是问题的简化版本,但是任何方向都将不胜感激。

SELECT    AAAREFNUMVALUE AS 'Alpha Pro Number',
          AAATRANSPORTTABLE AS 'Table ID',
          AAAREFNUMTYPE AS 'Number Type',
          (SELECT AAAREFNUMTYPE 
          FROM dbo.AAATOREFNUMS 
          WHERE AAAREFNUMTYPE = 2) AS 'Shippers BL#'
FROM          dbo.AAATOREFNUMS
WHERE        (AAAREFNUMTYPE = 1)

1 个答案:

答案 0 :(得分:0)

您可以使用子查询来执行此操作,但需要将其关联:

SELECT a.AAAREFNUMVALUE AS "Alpha Pro Number",
       a.AAATRANSPORTTABLE AS "Table ID",
       a.AAAREFNUMTYPE AS "Number Type",
       (SELECT a2.AAAREFNUMTYPE 
        FROM dbo.AAATOREFNUMS a2
        WHERE a2.AAATRANSPORTTABLE  = a.AAATRANSPORTTABLE  AND
             a2.AAAREFNUMTYPE = 2
       ) AS "Shippers BL#"
FROM dbo.AAATOREFNUMS a
WHERE AAAREFNUMTYPE = 1 ;

我强烈建议您不要使用单引号将标识符引起来。单引号应仅用于字符串和日期常量。我将它们更改为在大多数数据库中都可以使用的双引号。