【问题标题】:SQL, Find "Paths" in SQL-Rows (Group by / Distinct)?SQL,在 SQL 行中查找“路径”(分组方式/不同)?
【发布时间】:2019-03-29 07:48:41
【问题描述】:

希望有人可以帮助我解决这个 mysql 示例:

hash, version, action
a1..., A, pageview
a2..., A, pageview
a2..., B, pageview
a2..., X, lead
a3..., A, pageview
a3..., B, pageview
a4..., A, pageview
a4..., X, lead
a5..., B, pageview
a6..., A, pageview
a6..., X, lead

如何用一个语句回答以下问题?

  • 列出所有具有 version = A 行(仅!)和另一行 action=lead 的哈希
  • 列出具有 version = B 行(仅!)和另一行 action=lead 的所有哈希
  • 列出所有具有版本 A 的操作、具有版本 B 的另一行和具有 action=lead 的行的所有哈希

我用 select distinct 和 group by have 尝试了如下几个语句,但没有成功

SELECT *, count(hash) as count 
FROM it_track 
GROUP BY hash, action 
having count > 1 
   and action like 'lead';

非常感谢!

一月。

【问题讨论】:

  • 使用正确的GROUP BYGROUP BYSELECT * 是一个大红旗。事实上,它甚至不会为大多数 dbms 运行。

标签: mysql sql select distinct


【解决方案1】:

我想你想要这样的东西:

select hash,
       (case when sum(action = 'lead') and
                  min(version) = max(version) and
                  min(version) = 'A'
             then 'A-only, with lead'
             when sum(action = 'lead') and
                  min(version) = max(version) and
                  min(version) = 'B'
             then 'B-only, with lead'
             when sum(action = 'lead') and
                  min(version) <> max(version) 
             then 'Both, with lead'
             else 'Unknown'
      end) as which_group
from it_track
where (action = 'lead' or
       ( action = 'pageview' and version in ('A', 'B') )
      )
group by hash

【讨论】:

    【解决方案2】:

    另一个加入为的版本:

    1> select t1.hash from it_track t1, it_track t2 
       where t2.hash = t1.hash 
       and t1.version = 'A' 
       and t2.action ='lead';
    
    2> select t1.hash from it_track t1, it_track t2 
       where t2.hash = t1.hash 
       and t1.version = 'B' 
       and t2.action ='lead';
    
    3> select t1.hash from it_track t1, it_track t2 , it_track t3
       where t2.hash = t1.hash 
       and t3.hash = t1.hash
       and t1.version = 'A' 
       and t2.version = 'B'
       and t3.action ='lead';
    

    【讨论】:

    • @funnyJanni 如果有帮助也请检查一下
    【解决方案3】:
    1> select distinct t1.hash from it_track t1 where version = 'A' and exists (select 1 from it_track t2 where t1.hash = t2.hash and t2.action = 'lead');
    2> select distinct t1.hash from it_track t1 where version = 'B' and exists (select 1 from it_track t2 where t1.hash = t2.hash and t2.action = 'lead');
    3> select distinct t1.hash from it_track t1 where version = 'A' and exists (select 1 from it_track t2 where t2.hash = t1.hash and version = 'B') and exists (select 1 from it_track t3 where t3.action = 'lead' and t3.hash = t1.hash);
    

    【讨论】:

    • 嗨,对不起 ;-)。每个问题一个陈述;-)))
    猜你喜欢
    • 2013-03-15
    • 1970-01-01
    • 2023-03-24
    • 2011-04-22
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    相关资源
    最近更新 更多