答案 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;
答案 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