• sql 多行、一行 互转


    原始数据:

    期望数据:

    1 IF OBJECT_ID('temp_20170701','u') IS NOT NULL DROP TABLE temp_20170701
    2 
    3  CREATE TABLE temp_20170701 (
    4  ID INT PRIMARY KEY IDENTITY(1,1),
    5  NAME  NVARCHAR(50),
    6  Subjectname NVARCHAR(50),
    7  Score INT
    8  )
    View Code
     1 INSERT dbo.temp_20170701( Name, subjectname, Score )
     2 SELECT 'A','语文','20' UNION
     3 SELECT 'A','数学','30' UNION
     4 SELECT 'A','英语','40' UNION
     5 SELECT 'B','语文','50' UNION
     6 SELECT 'B','数学','60' UNION
     7 SELECT 'B','英语','70' UNION
     8 SELECT 'C','语文','80' UNION
     9 SELECT 'C','数学','90' UNION
    10 SELECT 'C','英语','100' UNION
    11 SELECT 'D','英语','100'
    View Code
    1 SELECT Name ,Score=STUFF((SELECT ','+CONVERT(NVARCHAR(max),Score) FROM temp_20170701 t1 WHERE t1.NAME=t2.NAME FOR XML PATH('')),1,1,'')
    2 FROM temp_20170701 t2 GROUP BY t2.NAME
    View Code
     

    原始数据:

    期望数据:

    1 CREATE TABLE temp_20170702 (
    2 ID INT PRIMARY KEY IDENTITY(1,1),
    3 NAME NVARCHAR(50),
    4 Score varchar(100)
    5 )
    View Code
    1 insert temp_20170702 (Name,Score)
    2 select 'A','30,40,20' union
    3 select 'B','60,70,50' union
    4 select 'C','90,100,80' union
    5 select 'D','100'
    View Code
    1 select a.NAME,b.value as Score from (
    2 select *,s=CONVERT(xml,'<root><v>'+REPLACE(Score,',','</v><v>')+'</v></root>') from temp_20170702 
    3 ) a outer apply 
    4 (select value=n.s.value('.','varchar(100)') from a.s.nodes('/root/v') n(s)) b
    View Code
  • 相关阅读:
    poj 3318 Matrix Multiplication 夜
    hdu 4331 Image Recognition 夜
    poj 3277 City Horizon 夜
    poj 3301 Texas Trip 夜
    poj 1151 Atlantis 夜
    poj 3286 How many 0's 夜
    poj 2454 Jersey Politics 夜
    poj 1465 Multiple 夜
    poj 1095 Trees Made to Order 夜
    Null和undefined的区别?
  • 原文地址:https://www.cnblogs.com/xiao-sheng/p/9573295.html
Copyright © 2020-2023  润新知