如何按列值分组?

时间:2018-02-28 20:31:03

标签: mysql sql

说我有这两张桌子

公司

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'

我是否需要某种子查询来实现这一目标?

1 个答案:

答案 0 :(得分:1)

您正在寻找group_concat

select ...  GROUP_CONCAT(tracking.Activity) as Activity

您还可以在活动和分隔符中指定顺序:

GROUP_CONCAT(tracking.Activity ORDER BY tracking.Activity SEPARATOR ', ')