如果您使用的是 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 |