从具有COALESCE的表中选择distinct(列名称)

时间:2015-03-17 15:35:53

标签: sql-server

我有一张这样的表,有很多记录。例如:

   HREFTopic                       PopularTopic                  LastModifiedTime
   ------------------------------------------------------------------------------
 //twitter.com/search?q=%23Happy    #Happy St. Patrick's Day    2015-03-17 19:57:18.000
 //twitter.com/search?q=%23Happy    #Happy St. Patrick's Day    2015-03-17 18:57:17.000
 //twitter.com/search?q=%23HappyV   #Happy Valentines Day   2015-03-17 17:57:15.000

这是我的存储过程

 declare @abc nvarchar(max)  
 declare @SearchKey nvarchar(max) 
 select @SearchKey ='Happy'
 select top 10   @abc =  COALESCE(@abc + '','') + '<li>' + '<a class="z" href="' +'../q.aspx?q=' + @SearchKey + '">' + (PopularTopic)  + '</a></li>' + char(10) + char(13)      
 from PopularTrends  where HREFTopic like    '%'+ @SearchKey +'%'   order by LastModifiedTime desc   

 select @abc 

,输出为(@abc)=

 <li><a class="z" href="../q.aspx?q=Happy">Happy St. Patrick's Day</a></li>
 <li><a class="z" href="../q.aspx?q=HappyV">Happy Valentines Day  </a></li> 
 <li><a class="z" href="../q.aspx?q=Happy">Happy St. Patrick's Day</a></li> 
 <li><a class="z" href="../q.aspx?q=Happy">Happy St. Patrick's Day</a></li> 
 <li><a class="z" href="../q.aspx?q=Happy">Happy St. Patrick's Day</a></li>
 <li><a class="z" href="../q.aspx?q=Happy">Happy St. Patrick's Day</a></li>
 <li><a class="z" href="../q.aspx?q=Happy">Happy St. Patrick's Day</a></li> 

但是我只需要LastModifiedTime的不同(PopularTopic)顺序,我希望结果是:

 <li><a class="z" href="../q.aspx?q=Happy">Happy St. Patrick's Day</a></li>
 <li><a class="z" href="../q.aspx?q=HappyV">Happy Valentines Day  </a></li>

我无法获得不同的(PopularTopic),而是获得所有记录。 有人可以帮助我获得正确的查询。

1 个答案:

答案 0 :(得分:0)

这应该这样做,并且学习使用FOR XML PATH进行字符串连接比使用的无证变量构建过程更好。互联网上有很多例子。

WITH cte AS (
 select top 10 PopularTopic, MAX(LastModifiedTime) AS LMT
 from PopularTrends  
 where HREFTopic like '%'+ @SearchKey +'%'  
 GROUP BY PopularTopic 
 order by LMT desc   
)
SELECT 
 (
  SELECT '<li><a class="z" href="../q.aspx?q='+@SearchKey+'">' + PopularTopic + '</a></li>' + char(10) + char(13)               
  FROM cte
  FOR XML PATH(''), root('h'), type
 ).value('/h[1]','varchar(max)')

而且,如果您刚从数据库返回前10个PopularTopics并处理应用层中的列表构建,那么,如果它值得,您将获得更好的整体性能。