获取ColumnHeader作为行值及其在另一列中的关联值?

时间:2015-07-01 09:49:58

标签: sql sql-server-2008 union pivot-table common-table-expression

我的表BankACTable:

BANK    ACNO    AC_SER      STATE  CITY
-----------------------------------------
ICICI   1220    0987654     MH      NGP
AXIS    4561    5786        AP      HYD
:       :       :           :       :
:       :       :           :       :   

我想要的只有这个形式:

ColumnName              ColumnValue
-------------------------------------
AccountName             ICICI           
Amount                  1220
RegistrationNumber      0987654
State                   Maharashtra
Address                 Nagpur
AccountName             AXIS    
Amount                  4561
RegistrationNumber      5786
State                   AP  
Address                 HYD

所有SQL英雄,PLZ帮我获得这个结果!

2 个答案:

答案 0 :(得分:0)

像这样使用UNPIVOT

SELECT COL,VAL
FROM (SELECT CONVERT(VARCHAR(30),[BANK])[AccountName], CONVERT(VARCHAR(30),[ACNO]) [Amount], CONVERT(VARCHAR(30),[AC_SER]) as [RegistrationNumber], CONVERT(VARCHAR(30),[STATE])[State], CONVERT(VARCHAR(30),[CITY])[Address] 
      FROM BankAC) BankAC
UNPIVOT(VAL FOR COL IN ([AccountName], [Amount], [RegistrationNumber], [State], [Address])) as upvt;

SQL Fiddle

<强>输出

|                COL |    VAL |
|--------------------|--------|
|        AccountName |  ICICI |
|             Amount |   1220 |
| RegistrationNumber | 987654 |
|              State |     MH |
|            Address |    NGP |
|        AccountName |   AXIS |
|             Amount |   4561 |
| RegistrationNumber |   5786 |
|              State |     AP |
|            Address |    HYD |

答案 1 :(得分:0)

不是/[\d\-|\.]*\.jar/ ,而是Pivot操作

Unpivot