小编典典

使用XML标记行以逗号分隔值

sql

我有2个名为“类别”和“ CSTagContent”的表,下面显示了数据…

表1:“类别”

CategoryID  PostID  <----Categories Table
 1148       581771  
 1183       581771  
 1184       581771

表2:’CSTagContent’

ID   TagContent       StartDate   EndDate   CategoryID      TagTitle     <---CSTagContent Table

 1 <blockquote><p>     2014-11-08 2014-11-14  1148       
   <a href="abc.com">
   </p></blockquote>
 2 <blockquote><p>     2014-11-25 2014-12-05  1183     <h1>Aging Title</h1> 
   <a href="abc.com">
   </p></blockquote>
 3 <blockquote><p>     2014-11-25 2014-11-27  1184     <h1>Allergies Title</h1> 
   <a href="abc.com">
   </p></blockquote>

我的查询:

SELECT 
    st.TagContent, st.TagTitle              
FROM 
    Categories cpc 
INNER JOIN
    CSTagContent st ON st.CategoryID = cpc.CategoryID
WHERE 
    cpc.PostID = 581771 
    AND st.TagContent IS NOT NULL 
    AND st.TagContent <> ''                                               
    AND GETDATE() > st.StartDate  
    AND GETDATE() < DATEADD(dd, 1, st.EndDate)

电流输出:

 TagContent             TagTitle

<blockquote><p>     
<a href="abc.com">    <h1>Aging Title</h1>
</p></blockquote>

<blockquote><p>      <h1>Allergies Title</h1> 
<a href="abc.com">
</p></blockquote>

在上面的输出TagContent中,两行具有相同的值,因此我希望它与众不同,TagTitle应将其与其他行/行附加或合并为’&’,如下所示…

预期产量:

   TagContent                    TagTitle

  <blockquote><p>     
  <a href="abc.com">    <h1>Aging Title</h1>&<h1>Allergies Title</h1> 
  </p></blockquote>

提前致谢..!


阅读 192

收藏
2021-03-17

共1个答案

小编典典

样品台

SELECT * INTO Categories
FROM
(
   SELECT 1148 CategoryId, 581771 PostId
   UNION ALL
   SELECT 1183 CategoryId, 581771 PostId
   UNION ALL
   SELECT 1184 CategoryId, 581771 PostId   
)TAB


SELECT * INTO TagContent
FROM
(
SELECT 1 [Id], '<blockquote><p><a href="abc.com"></p></blockquote>' TagContent ,    '2014-11-08' StartDate, '2014-11-14' EndDate,  1148 CategoryID, NULL TagTitle

UNION ALL   
SELECT  2, '<blockquote><p><a href="abc.com"></p></blockquote>',     '2014-11-25', '2014-12-05',  1183,     '<h1>Aging Title</h1>'


UNION ALL
SELECT  3, '<blockquote><p><a href="abc.com"></p></blockquote>',     '2014-11-25', '2014-11-27',  1184,     '<h1>Allergies Title</h1>' 
)TAB

现在我们将TagTitle相同的转换为Ambersand分隔值TagContent。由于使用XML格式,因此我们需要替换&gt, &lt and&amp to <, > and &

询问

SELECT DISTINCT TagContent,STUFF(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING(
        (SELECT '&' + TagTitle
        FROM TagContent T2 
        WHERE ST.TagContent=T2.TagContent 
        FOR XML PATH('')),2,200000),'&lt;','<'),'&gt;','>'),'&amp;','&'),'amp;',''),1,'') TagTitle
        FROM Categories CPC
        JOIN TagContent ST ON CPC.CategoryId=ST.CategoryId
2021-03-17