如何在两个表或一个详细表中规范化sql表

时间:2018-03-28 15:56:03

标签: sql sql-server unpivot

我想对我的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中执行此操作?有人可以帮帮我吗?

3 个答案:

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

您可以像这样使用UNPIVOT:

SELECT distinct ucode, desc, code, value
FROM 
(
SELECT *
FROM tbl_code
) AS cp
UNPIVOT (value
FOR code IN (code1, code2, code3)) AS up
Order by code;

输出将如下所示:

enter image description here