将多个简单查询转换为单个查询?

时间:2018-09-13 00:25:17

标签: sql database postgresql

我是SQL的新手,所以必须像5岁时一样对事物进行解释。我试图找出有多少人执行了该事件“单击了解更多”然后继续执行该事件“设置试用状态” 。我使用的是Postgres,因此还有一个AND payload->>'status' = true可以简化。本质上,我需要将以下伪查询转换为功能单一查询。

SELECT DISTINCT booking_id
FROM venue_events
WHERE name = 'clicked learn more'`;

SELECT count(*)
FROM venue_events
WHERE booking = booking_id AND name = 'set trial status' AND payload->>'status' = true;

如何将其本质上转变为一个SQL查询,第二个使用第一个中的booking_ids

下面是表格中的数据。

row layout

3 个答案:

答案 0 :(得分:1)

SELECT count(*)
FROM venue_events
WHERE name = 'set trial status' 
AND booking_id IN
(
    SELECT DISTINCT booking_id
    FROM venue_events
    WHERE name = 'clicked learn more'
)
AND payload->>'status' = true;

答案 1 :(得分:1)

很难完全确定表结构和样本数据,但是如果您想获得在另一个答案的注释中提到的所有计数,我认为此查询就是您所需要的。

SELECT v1.booking_id AS booking_id,
       COUNT(v1.booking_id) AS Clicked_learn_more, 
       COUNT(v2.booking_id) AS Set_trial_status_true,
       COUNT(v3.booking_id) AS Completed_booking
FROM (SELECT DISTINCT booking_id 
      FROM venue_events 
      WHERE name='clicked learn more' AND payload->>'status' = true) v1
LEFT JOIN (SELECT DISTINCT booking_id 
           FROM venue_events 
           WHERE name='set trial status' AND payload->>'status' = true) v2
    ON v2.booking_id = v1.booking_id
LEFT JOIN (SELECT DISTINCT booking_id 
           FROM venue_events 
           WHERE name='completed booking' AND payload->>'status' = true) v3
    ON v3.booking_id = v1.booking_id
GROUP BY v1.booking_id

答案 2 :(得分:0)

我认为您需要按名称分组

SELECT name ,count(*)
FROM venue_events
WHERE   payload->>'status' = true
group by name