SQL,在SQL行中查找“路径”(按/区分)?

时间:2018-10-24 19:37:53

标签: mysql sql select distinct

希望有人可以通过这个mysql-example帮助我

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

如何用一个陈述回答以下问题?

  • 列出所有具有版本= A(仅!)的行和具有action = lead的另一行的所有散列
  • 列出所有具有版本= B(仅!)的行和具有action = lead的另一行的所有散列
  • 列出所有具有版本A动作的哈希,另一个具有版本B的行以及具有action = lead的行

我尝试了以下类似的语句,并选择了“与众不同”和“分组”,但没有成功

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

非常感谢!

一月。

3 个答案:

答案 0 :(得分:0)

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);

答案 1 :(得分:0)

另一个加入方式为:

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';

答案 2 :(得分:0)

我认为您想要这样的东西:

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