说我有这两张桌子
公司
CompanyId
Name
State
Country
跟踪
Id
CompanyId
Activity
hitDate
现在我可以有一些这样的数据
公司表
1 Company1 AK USA
2 Company2 TX USA
追踪表
1 1 'First Page' 2018-01-01
2 1 'Second Page' 2018-01-01
3 2 'First Page' 2018-01-01
现在我想通过州和国家/地区将这些表连接在一起
SELECT
Count(*) as TotalCount,
company.State as State,
company.Country as Country,
tracking.Activity as Activity
FROM tracking
INNER JOIN companies
ON tracking.CompanyId=company.CompanyId
AND tracking.Activity IN ('First Page', 'Second Page')
AND companies.Country = 'USA'
AND DATE(tracking.dDateTime) BETWEEN '2018-02-27' AND '2018-02-28'
GROUP BY companies.State, companies.Country
ORDER BY companies.State
所以我写了一个像上面这样的查询,这会得到像
这样的结果Total Count - 1
State - AK
Country - USA
Activity - 'First Page'
Total Count - 1
State - AK
Country - USA
Activity - 'Second Page'
Total Count - 1
State - Tx
Country - USA
Activity - 'First Page'
但是我想让结果像这样
Total Count - 2
State - AK
Country - USA
Activity - 'First Page, Second Page'
Total Count - 1
State - Tx
Country - USA
Activity - 'First Page'
我是否需要某种子查询来实现这一目标?
答案 0 :(得分:1)
您正在寻找group_concat
:
select ... GROUP_CONCAT(tracking.Activity) as Activity
您还可以在活动和分隔符中指定顺序:
GROUP_CONCAT(tracking.Activity ORDER BY tracking.Activity SEPARATOR ', ')