我想对我的SQL规范化提供一些帮助。我有一张表如下:
tbl_code
Ucode, desc, code1, code2, code3
1 aa 1 1 1
2 bb 1 2 2
3 cc 1 1 1
现在我想将此表格规范化为:
ucode, desc, code, value
1 aa code1 1
2 bb code1 1
3 cc code1 1
1 aa code2 1
依旧......
我怎样才能在SQL中执行此操作?有人可以帮帮我吗?
答案 0 :(得分:1)
又一个选择
Select A.UCode
,A.[Desc]
,B.*
From tbl_code A
Cross Apply (
values ('code1',code1)
,('code2',code2)
,('code3',code3)
) B(code,value)
更新 - 动态而不使用动态SQL
Select A.Ucode
,A.[desc]
,C.*
From tbl_code A
Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData)
Cross Apply (
Select Code = a.value('local-name(.)','varchar(100)')
,Value = a.value('.','varchar(max)')
From B.XMLData.nodes('/row') as C1(n)
Cross Apply C1.n.nodes('./@*') as C2(a)
Where a.value('local-name(.)','varchar(100)') not in ('Ucode','desc')
-- {or you can use} Where a.value('local-name(.)','varchar(100)') like 'code%'
) C
答案 1 :(得分:0)
这应该让你前进,但你可能最终会得到NULL等等来处理现实生活?
SELECT
ucode,
[desc],
'code1' AS code,
code1 AS [value]
FROM
tbl_code
UNION ALL
SELECT
ucode,
[desc],
'code2' AS code,
code2 AS [value]
FROM
tbl_code
UNION ALL
SELECT
ucode,
[desc],
'code3' AS code,
code3 AS [value]
FROM
tbl_code;
答案 2 :(得分:0)