0

我在 sql 中有一个存储访问统计信息的表,并且有以下列:

referredURL

searchedWord(将用户引导至此页面的词)

Hittime

我想要一份包含下表的报告: - refferedURL - recenReferDate - allSearchedWors

select ReferredURL , MAX (HitTime) as 'Recent refer date'
from statTbl
GROUP BY ReferredURL

我在收集 allSearchedWords 时遇到问题,如何收集一个组的所有 searchedWord 并将其用作列?

4

1 回答 1

1

如果您使用的是 SQL Server,请尝试

SELECT t.ReferredURL, 
       MAX (t.HitTime) 'Recent refer date',
       (
         STUFF((SELECT DISTINCT ',' + SearchedWord 
                  FROM statTbl 
                 WHERE ReferredURL = t.ReferredURL 
                   FOR XML PATH('')) , 1 , 1 , '' ) 
       ) 'Searched Words'
  FROM statTbl t
 GROUP BY t.ReferredURL;

如果您需要所有单词都存在,甚至重复DISTINCT从子查询中删除。

这是SQL Server的SQLFiddle示例

如果是 MySql 那么

SELECT t.ReferredURL, 
       MAX(t.HitTime) 'Recent refer date',
       GROUP_CONCAT(DISTINCT(SearchedWord)) 'Searched Words'
  FROM statTbl t
 GROUP BY t.ReferredURL;

这是MySql 的SQLFiddle示例

样本数据

| REFERREDURL |                    HITTIME | SEARCHEDWORD |
-----------------------------------------------------------
|        url1 | May, 22 2013 00:00:00+0000 |        apple |
|        url1 | May, 22 2013 12:00:00+0000 |       banana |
|        url1 | May, 22 2013 18:00:00+0000 |         pear |
|        url1 | May, 22 2013 18:05:00+0000 |        apple |
|        url2 | May, 22 2013 23:00:00+0000 |        apple |

样本输出

| REFERREDURL |          RECENT REFER DATE |    SEARCHED WORDS |
----------------------------------------------------------------
|        url1 | May, 22 2013 18:05:00+0000 | apple,banana,pear |
|        url2 | May, 22 2013 23:00:00+0000 |             apple |
于 2013-05-22T06:38:05.870 回答