【问题标题】:concatenate a column on one line depends on a id在一行上连接一列取决于 id
【发布时间】:2017-07-03 10:04:50
【问题描述】:

我又问了一个基本问题:

如果我这样做:

SELECT DISTINCT id, date, doctext, docline, from documentation where date in (02/14/2017)

doctext 是char(80),我无法更改它。此列的问题是大小,我无法保存> 80个字符的值,如果文档> 80个字符,它将在SQL中保存两行并升级文档

所以我的结果是,例如:

0 2017-02-14 this is a basic test to show you the result 0
1 2017-02-14 this is a new basic test to show you the result 0
2 2017-02-14 this is a  long basic test to show you the result 0
2 2017-02-14 when the documentation have multiple lines 1

如果结果有多个具有相同 id 的行,我想要做的是连接 doctext 所以结果应该是:

0 2017-02-14 this is a basic test to show you the result 
1 2017-02-14 this is a new basic test to show you the result 
2 2017-02-14 this is a  long basic test to show you the result when the documentation have multiple lines 1

是否可以根据 id 在一行上连接一列? 我正在尝试使用 CASE,例如:

CASE WHEN docline > 0 THEN DOCTEXT ... 

我不知道如何指定我想要下一个 DOCTEXT

谢谢,

【问题讨论】:

    标签: sql-server concatenation


    【解决方案1】:

    这样的东西应该可以工作

    SELECT id, date,MAX(docline),
    Ids=Stuff((SELECT ' ' + doctext  FROM documentation  d WHERE d.id=documentation.id
     FOR XML PATH (''))
                 , 1, 1, '' )
     from documentation where date in (02/14/2017)
    GROUP BY id,date
    

    【讨论】:

    • 只有当我在文档中有一个值时它才有效,因为如果我有 ;ore 然后是 1 个文档,它将连接 1 中的所有文档
    • @FannyV 你叫什么文档? .尝试更精确
    • 文档用于 doctext。谢谢你的帮助 !我今天(再次)学到了新东西!我没有工作(还),因为我的查询更复杂,但你修复并帮助了我很多!!!
    【解决方案2】:

    For storing multiple lines you used the docline column but I didn't use it. if you want you can add it.

    I used two tables(MasterTable and DetailsTable)

    Master Table:

    ID | Date | DocText
    -----------------------------
    1 2017-01-14 Hello
    -----------------------------
    2 2017-03-18 Good Bye
    ------------------------------
    3 2017-02-14 Hello Iran
    ------------------------------
    4 2017-02-14 Good Bye Iran
    ------------------------------

    DetailsTable:

    ID | DocText
    ---------------------------
    3 How are you ?
    ---------------------------
    4 See you ?
    ---------------------------

    Use Test;
    go

    select mt.ID,mt.DocText + ' ' + ISNULL(dt.DocText,'') as DocText
    from MasterTable mt
    full outer join DetailsTable dt
    on mt.ID=dt.ID;

    It works for multiple lines.

    the result:

    ID | Date | DocText
    --------------------------------------------
    1 2017-01-14 Hello
    --------------------------------------------
    2 2017-03-18 Good Bye
    --------------------------------------------
    3 2017-02-14 Hello Iran How are you ?
    --------------------------------------------
    4 2017-02-14 Good Bye Iran See you ?
    --------------------------------------------

    【讨论】:

    • 感谢您的帖子,但如果我没记错的话,我需要更改列表吗?并创建一个新表?就像我之前所说的,我无法更改我的数据库结构
    猜你喜欢
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 2021-02-25
    • 2021-12-20
    • 2014-07-29
    • 1970-01-01
    相关资源
    最近更新 更多