【问题标题】:combining similar data in MySQL在 MySQL 中组合相似的数据
【发布时间】:2016-11-15 11:32:42
【问题描述】:

我有以下数据:

 date     | source              | session | device
 5/1/2016 | facebook.com/social | 5       | mobile
 5/1/2016 | facebook.com/post   | 50      | desktop
 5/1/2016 | facebook.com/commun | 25      | mobile
 5/1/2016 | pintrest.com/social | 15      | mobile
 5/1/2016 | pintrest.com/commun | 25      | mobile

我需要这样的数据:

 date     | source              | session | device
 5/1/2016 | facebook            | 30      | mobile
 5/1/2016 | facebook            | 50      | desktop
 5/1/2016 | pintrest            | 40      | mobile

我正在使用 MySQL 数据库

【问题讨论】:

  • 你做了什么来满足你的需求?
  • 你已经尝试过什么?究竟是什么,你坚持?
  • 您的数据不匹配。源将50 | desktop 作为唯一的桌面行,但您的预期结果中包含65 | desktop。此外,您没有阐明任何要遵循的规则; source 是否应该缩短为第一个 . 之前的所有内容?或者部分数据可以有www.facebook.com吗?然后,我假设您想按data, shortened_source, device 分组?

标签: mysql sql hive hiveql


【解决方案1】:

假设您可以使用第一次出现的点作为您的缩短 URL ('.'),那么以下将适用于您。

select
  date
  , LEFT(source, LOCATE('.', source) - 1) as 'short_source'
  , sum(sessions) as  'sessions'
  , device
from date
group by 
  date
  , LEFT(source, LOCATE('.', source) - 1)
  , device

SQL Fiddle

好的,如果表中包含无效的 URL(在这种情况下是不带 DOT 的 url),请注意:

select
  date
  , COALESCE(LEFT(source, LOCATE('.', source) - 1), 'invalid_url') as 'short_source'
  , sum(sessions) as  'sessions'
  , device
from date
group by 
  date
  , LEFT(source, LOCATE('.', source) - 1)
  , device

【讨论】:

  • 还假设字符串中总是至少有一个.
  • 当然 - 但是,鉴于问题不明确,我认为最好继续下去......
猜你喜欢
  • 2011-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 1970-01-01
  • 2020-01-28
  • 2018-10-16
  • 2013-05-22
相关资源
最近更新 更多