表A
P Q R
1 A a
2 B a
3 C b
4 D b
如何将其转换为
表B
P a b
1 A -
2 B -
3 - C
4 - D
提示:a与A和B一起映射而不是表A中的C& D.类似地,b与C& D映射而不是A& B.枢轴不工作。请帮忙。
答案 0 :(得分:1)
这可以使用Dynamic CrossTab实现。供参考:http://www.sqlservercentral.com/articles/Crosstab/65048/
示例数据
CREATE TABLE SampleData(
P INT,
Q CHAR(1),
R CHAR(1)
)
INSERT INTO SampleData
SELECT 1, 'A', 'a' UNION ALL
SELECT 2, 'B', 'a' UNION ALL
SELECT 3, 'C', 'b' UNION ALL
SELECT 4, 'D', 'b'
动态交叉表
DECLARE @sql1 VARCHAR(4000) = '',
@sql2 VARCHAR(4000) = '',
@sql3 VARCHAR(4000) = ''
SELECT @sql1 =
'SELECT
P' + CHAR(10)
SELECT @sql2 = @sql2 +
' ,MAX(CASE WHEN R = ''' + R + ''' THEN Q END) AS [' + R + ']' + CHAR(10)
FROM(
SELECT DISTINCT R FROM SampleData
)t
ORDER BY R
SELECT @sql3 =
'FROM SampleData
GROUP BY P
ORDER BY P
'
PRINT(@sql1 + @sql2 + @sql3)
EXEC(@sql1 + @sql2 + @sql3)
<强> RESULT 强>
P a b
----------- ---- ----
1 A NULL
2 B NULL
3 NULL C
4 NULL D
答案 1 :(得分:0)
试试这个
select P,
case when R='a' then a else '-' end as a,
case when R='b' then '-' else a end as b
from table_A