zoukankan      html  css  js  c++  java
  • Mssql合并列值(三个关系表合并)

    第一个表: ID Name
                  1     wjy

    第二个表 : ID Menu

                  1 第一个
                  2 第二个
                  3 第三个


    第三个关系表: ID OneID TwoID
                         1     1      1
                        2      1      2
                        3      1       3

    首先:要通过上面三个表要得到下面的一个表:

    第一列 第二列 第三列
    1        wjy     1,2,3

    实现的代码:

    create table t1(ID int,Name varchar(10))
    insert into t1 select 1,'wjy'
    create table t2(ID int,Menu varchar(10))
    insert into t2 select 1,'第一个'
    insert into t2 select 2,'第二个'
    insert into t2 select 3,'第三个'
    create table t3(ID int,OneID int,TwoID int)
    insert into t3 select 1,1,1
    insert into t3 select 2,1,2
    insert into t3 select 3,1,3
    go
    select a.id 第一列,a.name 第二列,stuff((select ','+ltrim(TwoID) from t3 where OneID=a.id for xml path('')),1,1,'')第三列
    from t1 a group by a.id,a.name
    /*
    第一列         第二列        第三列
    ----------- ---------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    1           wjy        1,2,3

    (1 行受影响)

    */
    go
    drop table t1,t2,t3

     

     

    第二种写法:要得到另一种表

     

    第一列 第二列 第三列
    1        wjy     第一个,第二个,第三个

     

    create table t1(ID int,Name varchar(10))
    insert into t1 select 1,'wjy'
    go
    create table t2(ID int,Menu varchar(10))
    insert into t2 select 1,'第一个'
    insert into t2 select 2,'第二个'
    insert into t2 select 3,'第三个'
    go
    create table t3(ID int,OneID int,TwoID int)
    insert into t3 select 1,1,1
    insert into t3 select 2,1,2
    insert into t3 select 3,1,3
    go
    select a.id 第一列,a.name 第二列,
       
    stuff((select ','+e.Menu from t3 t join t2 e on t.TwoID=e.ID where OneID=a.id for xml path('')),1,1,'')第三列
    from t1 a group by a.id,a.name

    drop table t1,t2,t3

    /********************

    第一列         第二列        第三列
    ----------- ---------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    1           wjy        第一个,第二个,第三个

    (1 行受影响)

  • 相关阅读:
    #最小生成树,Trie#CF888G Xor-MST
    #Tarjan#洛谷 5676 [GZOI2017]小z玩游戏
    #区间dp#CF1114D Flood Fill
    #构造,二分#[AGC006B] [AGC006D] Median Pyramid
    #0/1分数规划#AT1807 食塩水
    #笛卡尔树#洛谷 3793 由乃救爷爷
    #同余最短路#洛谷 2371 [国家集训队]墨墨的等式
    awk命令使用
    k8s快速删除所有退出的pod
    ratticdb密码管理工具安装使用
  • 原文地址:https://www.cnblogs.com/wujy/p/2168013.html
Copyright © 2011-2022 走看看