要列出的SQL列

时间:2016-05-18 07:45:37

标签: tsql unpivot

我有以下表格内容: -

Table Structure

我需要产生以下输出: -

P1 C1
P1 C3
P2 C1
P2 C4
P3 C2
P3 C3
P3 C4

如何从我的表格中创建该列表?

由于

P

3 个答案:

答案 0 :(得分:3)

您必须使用UnPivot来获得所需的结果

    DECLARE @MyTable TABLE
(Attribute VARCHAR(10) , C1 VARCHAR(10), C2 VARCHAR(10), C3 VARCHAR(10), C4 VARCHAR(10))

INSERT INTO @MyTable VALUES
('P1','X', NULL,'X',NULL), ('P2','X',NULL,NULL,'X'),('P3',NULL,'X','X','X')

SELECT * FROM @MyTable

SELECT uPivot.Attribute, uPivot.Quatr, uPivot.IsMarked
FROM @MyTable Tab1
UNPIVOT
        (
          IsMarked
          for Quatr in (C1, C2, C3, C4)
        ) uPivot;

SQL FIDDLER EXAMPLE

答案 1 :(得分:1)

这应该基于所提供的信息而有效。

select u.P, -- whatever the column containing p1, p2, etc is called
u.C,
u.Contents -- what is stored in each cell
from xtable
unpivot
(
  Contents
  for C in (c1, c2, c3)
) u
where u.Contents like 'x'

http://sqlfiddle.com/#!3/4d908/1/0

我几乎略微修改了Ako在评论中链接的例子。

答案 2 :(得分:0)

这是我最后实施的解决方案

DECLARE @SQL NVARCHAR(MAX)
DECLARE @ColName TABLE (Name VARCHAR(500))
DECLARE @ColCSV VARCHAR(MAX)

INSERT INTO  @ColName 
SELECT
    Column_Name
FROM
    information_schema.columns
WHERE
    Table_Name = 'SMC_PatientCondition'
    AND Column_Name NOT IN 
        ('ReportingCode',
        'P_PatientId',
        'P_SysId',
        'Condition')

SET @ColCSV = (SELECT SUBSTRING((SELECT ',' + Name FROM @ColName FOR XML PATH ('')),2,2000) AS CSV)

SET @SQL =
('
SELECT
    P_SysID,
    Conditions
FROM
    (
        SELECT
            P_SysId,
            RIGHT(Conditions, LEN(Conditions)-2) Conditions,
            HasCondition
        FROM
            SMC_PatientCondition
        UNPIVOT
        (
            HasCondition FOR Conditions IN ('+ @ColCSV +')
        )Con
    ) UserConditions
WHERE
    HasCondition = ''Yes''
')

EXEC sp_executesql @SQL