如何使用CTE汇总数据

问题描述 投票:0回答:1

我正在尝试根据给定的 event_code 获取事件参与者的摘要。如果事件是父事件,则摘要应基于所有子事件。如果它是单个事件(不是父事件并且没有父事件),则摘要基于单个事件。

提前致谢!

表格 (https://i.sstatic.net/flMqjD6t.png)

WITH selectedEvent  AS (
    SELECT
        event.Event_code              AS Event_code,
        event.parent_code        AS parent_code,
        attguest.attended        AS attevent,
        cont.gender AS Gender
    FROM
        event event
        INNER JOIN EventAttendance att 
        ON event.event_code = att.event_code
        INNER JOIN EventGuestAttendance  attguest 
        ON att.Event_attendance_code = attguest.Event_attendance_code
        LEFT JOIN contact cont
        ON attguest.Contact_code=cont.Contact_code
        WHERE attguest.Contact_code is not null
        AND attguest.Attended='1' 
        --
        AND event.event_code=(Parent event or single event)
)
SELECT
    eOne.eOneID,
    eone.eOneParent
    
FROM selectedEvent eOne

我创建了上面的查询来获取所有活动参与者,但查询仍然存在问题

sql oracle oracle11g
1个回答
0
投票

您想要使用分层查询来查找

Event
表中的所有后代,然后
JOIN
查找该表,然后使用条件聚合来
COUNT
每个性别的联系人。

类似:

SELECT COUNT(c.contact_code) AS total_contact_attendance,
       COUNT(CASE c.gender WHEN 'Female' THEN c.contact_code END) AS female,
       COUNT(CASE c.gender WHEN 'Male' THEN c.contact_code END) AS male
FROM   (
         SELECT CONNECT_BY_ROOT event_code AS root_event_code,
                event_code
         FROM   event
         START WITH event_code = 1
         CONNECT BY PRIOR event_code = parent_code
       ) e
       INNER JOIN EventAttendance a
       ON e.event_code = a.event_code
       INNER JOIN EventGuestAttendance g
       ON a.Event_attendance_code = g.Event_attendance_code
       LEFT JOIN contact c
       ON g.Contact_code = c.Contact_code
WHERE  g.Contact_code is not null
AND    g.Attended = 1
GROUP BY e.root_event_code

注意:这未经测试,因为您的数据位于图像中,这是我们无法轻松访问的格式。

© www.soinside.com 2019 - 2024. All rights reserved.