在一行上连接一列取决于id

时间:2017-02-14 22:45:10

标签: sql-server concatenation

我再次提出一个基本问题:

如果我这样做:

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

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

所以我的结果是,例如:

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

谢谢,

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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 ?
--------------------------------------------