SQL Pivot用于连续多个列

时间:2016-06-30 10:27:53

标签: sql sql-server sql-server-2008

我的表结构如

module load Python/2.7.11-foss-2016a
curl -O https://bootstrap.pypa.io/get-pip.py
python get-pip.py --user --upgrade
rm get-pip.py
.local/bin/pip install --user --upgrade pip

git clone https://github.com/tensorflow/tensorflow
git clone https://github.com/bazelbuild/bazel.git
wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u92-b14/jdk-8u92-linux-x64.tar.gz
tar -xf jdk*
rm jdk*.gz
cd bazel
export JAVA_HOME=~/jdk1.8.0_92/
module unload GCC/4.9.3-2.25
module load GCC/4.8.2
./compile.sh
cd ../tensorflow
export PATH=/home/ulg/sysmod/gmath/bazel/output/:$PATH
./configure
bazel build -c opt //tensorflow/tools/pip_package:build_pip_package 2>/dev/null
bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
cd
.local/bin/pip install --user --upgrade /tmp/tensorflow_pkg/tensorflow-0.8.0-py2-none-any.whl

我需要将表格转到

----------------------------------------------
AccountNo | Ben1 | Ben2 | Ben3 | Ben4 | Type |
----------------------------------------------
A1234     | xyz1 | xyz2 | xyz3 | xyz4 | P    |
A1005     | pqr1 | pqr2 | pqr3 | pqr4 | C    |
----------------------------------------------

通过sql查询我如何转向以获得上述结果

3 个答案:

答案 0 :(得分:3)

SELECT AccountNo, Name, Type
FROM
(
    SELECT AccountNo, Ben1, Ben2, Ben3, Ben4, Type
    FROM yourTable
) AS t1
UNPIVOT 
(
    Name FOR Names IN (Ben1, Ben2, Ben3, Ben4)
) AS t2

SQL Server UNPIVOT

<强>更新

您无法直接忽略NULL个值,因为这些记录将从结果集中删除。一种选择是将NULL VARCHAR列替换为文本'NULL'。这至少可以让您保留所有原始信息,同时还能看到原来的NULL

SELECT AccountNo, Name, Type
FROM
(
    SELECT AccountNo,
           COALESCE(Ben1, 'NULL'),
           COALESCE(Ben2, 'NULL'),
           COALESCE(Ben3, 'NULL'),
           COALESCE(Ben4, 'NULL'),
           Type
    FROM yourTable
) AS t1
UNPIVOT 
(
    Name FOR Names IN (Ben1, Ben2, Ben3, Ben4)
) AS t2

答案 1 :(得分:0)

可以使用 UNPIVOT

来完成
CREATE TABLE #TestTb(AccountNo VARCHAR(5),Ben1 VARCHAR(5), Ben2 VARCHAR(5), Ben3 VARCHAR(5), Ben4 VARCHAR(5), Type CHAR(1));

INSERT INTO #TestTb(AccountNo,Ben1,Ben2,Ben3,Ben4,Type)
VALUES ('A1234','xyz1','xyz2','xyz3','xyz4','P'),
    ('A1005','pqr1','pqr2','pqr3','pqr4','C');

SELECT  AccountNo,
        Name,
        Type
FROM (
        SELECT AccountNo,Ben1,Ben2,Ben3,Ben4,Type
        FROM #TestTb
    ) AS Src
    UNPIVOT (
        Name FOR AccName IN(Ben1,Ben2,Ben3,Ben4)
    ) AS UNPVT;

答案 2 :(得分:0)

另一种方法是使用UNION ALL

SELECT AccountNo, Ben1 as Name, [Type]
FROM YourTable
UNION ALL
SELECT AccountNo, Ben2, [Type]
FROM YourTable
UNION ALL
SELECT AccountNo, Ben3, [Type]
FROM YourTable
UNION ALL
SELECT AccountNo, Ben4, [Type]
FROM YourTable
ORDER BY AccountNo, Name

输出:

AccountNo   Name    Type
A1005       pqr1    C
A1005       pqr2    C
A1005       pqr3    C
A1005       pqr4    C
A1234       xyz1    P
A1234       xyz2    P
A1234       xyz3    P
A1234       xyz4    P