在ssms中将数据转换为列的简单方法

时间:2014-06-18 22:30:12

标签: sql pivot ssms transpose

这是我的剧本:

SELECT     
  LEFT(NARRKEY, 15) AS Business, 
  SUBSTRING(NARRKEY, 14, 10) AS [Sales Order], 
  SUBSTRING(NARRKEY, 24, 3) AS LINE, 
  NARRLINE$1 + ' ' + NARRLINE$2 + ' ' + NARRLINE$3 + ' ' + NARRLINE$4 + ' ' + NARRLINE$5 + ' ' + NARRLINE$6 + ' ' + NARRLINE$7 AS Text, 
  CASE 
    WHEN NARRPREFIX = 'J' THEN 'HEADER TEXT' 
    WHEN NARRPREFIX = 'I' THEN 'LINE TEXT' 
    ELSE NULL 
  END AS Expr2
 FROM   dbo.MAA040
 WHERE  (NARRLANG = 'E') 
 AND    (NARRSEQ = '000') 
 AND (NARRPREFIX = 'J' OR NARRPREFIX = 'I')

我希望能够将当前列NARRPREFIX更改为两个新列,即HEADER TEXT和LINE TEXT,在两个新列中,我将使文本列中的数据依赖于它是否为头文本填充标题列或行文本,填充行列

1 个答案:

答案 0 :(得分:0)

SELECT     
  LEFT(NARRKEY, 15) AS Business, 
  SUBSTRING(NARRKEY, 14, 10) AS [Sales Order], 
  SUBSTRING(NARRKEY, 24, 3) AS LINE, 
  NARRLINE$1 + ' ' + NARRLINE$2 + ' ' + NARRLINE$3 + ' ' + NARRLINE$4 + ' ' + NARRLINE$5 + ' ' + NARRLINE$6 + ' ' + NARRLINE$7 AS Text, 
  CASE 
    WHEN NARRPREFIX = 'J' THEN 'HEADER TEXT' 
    WHEN NARRPREFIX = 'I' THEN 'LINE TEXT' 
    ELSE NULL 
  END AS Expr2,
CASE WHEN NARRPREFIX = 'J' THEN NARRLINE$1 + ' ' + NARRLINE$2 + ' ' + NARRLINE$3 + ' ' + NARRLINE$4 + ' ' + NARRLINE$5 + ' ' + NARRLINE$6 + ' ' + NARRLINE$7 END AS HeaderText,
CASE WHEN NARRPREFIX = 'I' THEN NARRLINE$1 + ' ' + NARRLINE$2 + ' ' + NARRLINE$3 + ' ' + NARRLINE$4 + ' ' + NARRLINE$5 + ' ' + NARRLINE$6 + ' ' + NARRLINE$7 END AS LineText

 FROM   dbo.MAA040
 WHERE  (NARRLANG = 'E') 
 AND    (NARRSEQ = '000') 
 AND (NARRPREFIX = 'J' OR NARRPREFIX = 'I')