仅在一个表中,仅在第二个表中以及在两个表中的条目的百分比

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

我有两个具有公用键的表,并且我正在尝试查询显示以下内容的结果:仅在first表(PC)中存在的条目的百分比,仅在second表(电话)中存在的条目的百分比以及在present中存在的条目的百分比两个表。总百分比应总计为100%。

Table name: PC
user_Id     Page
1322       page_1_PC
7223       page_20_PC    
1032       page_7_PC
366        page_3_PC 
....
Table name: phone
user_Id     Page
123       page_1_phone
300       page_72_phone   
1322      page_7_phone
3662      page_3_phone
....

所需的输出将是这样的:

platform     percentage
PC_only      23%
phone_only   36%   
both         41%
....

我得到的最远的是下面的内容,它仅显示一个表中存在的用户总数,而不是其他表中的用户总数,但我被卡住了。最好不要使用UNION,因为我不想多次查询表:

SELECT COUNT(user_Id) AS PC_only FROM PC WHERE NOT EXISTS 
(SELECT * FROM phone WHERE PC.user_Id = phone.user_Id)

mysql sql select exists
1个回答
0
投票

这里是一种方法:

select count(*) as total_entries, sum(pc) as in_pc, sum(phone) as in_phone,
       avg(pc) as in_pc, avg(phone) as in_phone,
       avg( pc = 1 and phone = 1 ) as in_both
from ((select distinct user_id, 1 as pc, 0 as phone
       from pc
      ) union all
      (select distinct user_id, 0, 1
       from phone
      ) 
     ) p;
© www.soinside.com 2019 - 2024. All rights reserved.