SQL Multiple Selects和Group Bys

时间:2016-04-12 15:09:25

标签: mysql sql select conditional

这是我的数据:

enter image description here

我想找到满足以下条件的每个日期的唯一SessionId数: 当" / topic"的数量在一个sessionid = 1中," / detail"在同一个sessionid中也等于1.因此对于我的情况,sessionid = 1(412)是唯一满足要求的sessionid。

这是我使用的代码:(表名是我们)

SELECT count( Distinct sessionid) 
from
    ( Select sessionid, count(search like "/topic%") as TN and Count(search like "/detail%") as DN from we GROUP BY date order by date) as my_table 
WHERE TN ==1 and DN=1

对于凌乱的代码感到抱歉,但它应该打印出日期412和日期413的[1,0]。但它不起作用。任何建议?很多人!

2 个答案:

答案 0 :(得分:1)

您使用子查询处于正确的轨道上。您的语法有点偏离(例如,使用sum()而不是count())并且group by键不正确。但是,你似乎在寻找:

select date, count(Distinct sessionid)
from (select date, sessionid,
             sum(search like "/topic%") as TN, sum(search like "/detail%") as DN
      from we
      group by date, sessionid
     ) t
whereTN = 1 and DN = 1
group by date;

答案 1 :(得分:1)

SELECT DATE, 
       count(Distinct sessionid) 
FROM (Select sessionid, 
             DATE,
             SUM(CASE WHEN search like '/topic%' THEN 1 ELSE 0 END) as TN, 
             SUM(CASE WHEN search like '/detail%' THEN 1 ELSE 0 END) as DN 
    from we 
    GROUP BY sessionid, DATE
    ) as my_table 
WHERE TN = 1 AND DN = 1
GROUP BY DATE