1

是否可以在没有逐行处理的情况下在 SQL Server 2005 中执行以下操作?如果是这样,怎么做?:)

我的桌子是这样的:

╔════════════╦═══════════╦════════════╗
║ CustomerID ║ FirstName ║  LastName  ║
╠════════════╬═══════════╬════════════╣
║          1 ║ George    ║ Washington ║
║          2 ║ Benjamin  ║ Franklin   ║
║          3 ║ Thomas    ║ Jefferson  ║
╚════════════╩═══════════╩════════════╝

我这样输出上表:

╔════════════╦══════════╦════════════╗
║   Field    ║ IntValue ║ TextValue  ║
╠════════════╬══════════╬════════════╣
║ CustomerID ║ 1        ║ NULL       ║
║ FirstName  ║ NULL     ║ George     ║
║ LastName   ║ NULL     ║ Washington ║
║ CustomerID ║ 2        ║ NULL       ║
║ FirstName  ║ NULL     ║ Benjamin   ║
║ LastName   ║ NULL     ║ Franklin   ║
║ CustomerID ║ 3        ║ NULL       ║
║ FirstName  ║ NULL     ║ Thomas     ║
║ LastName   ║ NULL     ║ Jefferson  ║
╚════════════╩══════════╩════════════╝

谢谢!杰森

4

2 回答 2

2

虽然我仍然建议在使用 SELECT 的层执行这种旋转要好得多,但这里有一个想法。

DECLARE @x TABLE(CustomerID INT, FirstName VARCHAR(32), LastName NVARCHAR(32));

INSERT @x SELECT 1, 'George', 'Washington'
UNION ALL SELECT 2, 'Benjamin', 'Franklin'
UNION ALL SELECT 3, 'Thomas', 'Jefferson';

;WITH x AS
(
  SELECT 
    Field = 'CustomerID', IntValue = CustomerID, TextValue = NULL,
    rn = ROW_NUMBER() OVER (ORDER BY CustomerID)
    FROM @x
  UNION ALL
  SELECT 
    Field = 'FirstName', NULL, FirstName,
    rn = ROW_NUMBER() OVER (ORDER BY CustomerID)
    FROM @x
  UNION ALL
  SELECT
    Field = 'LastName', NULL, LastName,
    rn = ROW_NUMBER() OVER (ORDER BY CustomerID)
    FROM @x
)
SELECT Field, IntValue, TextValue
FROM x
ORDER BY rn, Field;

为什么在稍后的演示文稿中这样做会更好?因为这个“解决方案”会扫描表 3 次。消费者仍然必须使用循环来显示结果......

于 2012-05-24T17:06:56.033 回答
1

这只会扫描一次表(从@Aaron 的答案中借用表变量)。

SELECT Field, 
       IntValue, 
       TextValue 
FROM   @x 
       CROSS APPLY (SELECT 'CustomerID', CustomerID,  NULL 
                    UNION ALL 
                    SELECT 'FirstName', NULL, FirstName
                    UNION ALL 
                    SELECT 'LastName', NULL, LastName) 
        CA(Field, IntValue, TextValue) 
ORDER BY CustomerID  
于 2012-05-24T18:00:51.837 回答