无法找出要提问的SQL查询

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

相关:

Person1_UID Person2_UID   Type
1           2             club member
1           9             family
1           11            colleague
2           4             friend
2           7             colleague
3           4             club member
3           6             colleague
3           9             friend
3           10            follower
4           6             family
4           10            family
5           8             family
6           11            colleague
7           8             colleague
8           11            friend

DAY_PACKAGE:

DID Description    UID  VID
1   Spa Day         1   19
1   Spa Day         2   20
1   Spa Day         9   17
2   Adventure Time  4   16
2   Adventure Time  6   16
3   Family Fun Day  3   18
3   Family Fun Day  4   17
3   Family Fun Day  7   18
3   Family Fun Day  10  19
4   Relaxation Date 5   20

UID: User ID
DID: Day Package ID
VID: Voucher ID

根据上面的表格,找到参与者人数最多的日间套餐,其中所有参与者都以“家庭”或“俱乐部成员”的身份相互关联。

查询应返回:

DID Description Participant_Count
1   Spa Day         3
2   Adventure Time  2  

请各位好心人帮助我,谢谢!我已经被困在这个问题上好几个小时了。 TT

我只知道如何返回参与者总数:

SELECT Description, COUNT(DISTINCT UID) AS Participants_Count
FROM DAY_PACKAGE
GROUP BY Description
ORDER BY Participants_Count DESC
sql count subquery
1个回答
0
投票

问题的解决方案:

WITH CTE AS
(
  SELECT dp1.DID,
  dp1.Description,
  dp1.uid as uid1,
  dp2.uid as uid2,
  COUNT(*) OVER(PARTITION BY dp1.DID,dp1.UID) as total_participants,
  COUNT(r.type in ('club member','family') or dp1.UID = dp2.UID) 
  OVER(PARTITION BY dp1.DID,dp1.UID) as related_participants
  FROM day_package dp1
  LEFT JOIN day_package dp2
  ON dp1.did = dp2.did
  LEFT JOIN related r
  ON dp1.UID = r.person1_uid AND dp2.UID = r.person2_UID
)
SELECT DISTINCT DID,
  Description,
  related_participants as Participant_Count
FROM CTE
WHERE related_participants = total_participants
AND total_participants != 1
ORDER BY DID,Participant_Count

DB 小提琴链接 - https://dbfiddle.uk/tcV6ob2I

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