数据分析面试题

sql外连接只会返回主表条数数据?_sql外连接只显示一张表的数据吗-CSDN博客

连续出现N次类型:

  1. A表有5行数据,B表有3行数据,A join B,A left join B各会输出多少条数据

答:

普通内连接 (A JOIN B匹配键是唯一的): 如果A表和B表的连接基于某些键是匹配的,那么结果集将只包含那些在两个表中都能找到匹配行的记录。由于A表有5行,B表有3行,但实际匹配的数据可能会少于这个总和,取决于具体的连接条件。如果每行A都有对应的B表中的行,结果将是匹配行数;如果不是,结果将只有匹配的部分。

左外连接 (A LEFT JOIN B匹配键是唯一的): 这种情况下,A表的所有5行数据都会被包含在结果集中,即使在B表中没有找到匹配的行。对于A表中每一行,如果能找到B表中的匹配行,列值将取自B表;如果没有,列值通常为NULL。因此,结果集会有A表的5行,加上B表中匹配的3行,以及A表剩余2行的NULL值填充。

匹配键不唯一:可能会产生笛卡

  1. SQL的行转列操作

原始数据:

  1. sum + if(case when)

SELECT id,  

      sum(if(subject='MATH', score, NULL)) as `MATH`,  

      sum(if(subject='ENGLISH', score, NULL)) as `ENGLISH`,

      sum(if(subject='CHINESE', score, NULL)) as `CHINESE`

FROM score

GROUP BY id

Case when:

Select id,

Sum(case when subject='MATH' then score end) as ‘MATH’,

Sum(case when subject=’ENGLISH’ then score end) as ‘ENGLISH’,

Sum(case when subject=’CHINESE’ then score end) as ’CHINESE’

From score

Group by id

转行:

Select id,’MATH’ as subject,MATH as score from score

Union all

Select id,’ENGLISH’ as subject,ENGLISH as score from score

Union all

Select id,’CHINESE’as subject,CHINESE as score from score

Order by name

3.一张用户交易记录表buyer trade,3个字段:日期p date(yyyymmdd)/订单order id/买家 buyer id,想看-下用户在2024年3月如果有购买后,在接下来的30天里是否还会购买。最后统计该月份的复购人数占比?
select
month(a.p_day) as Month,
count(distinct b.buyer_id) as repeat_buyers,
count(distinct a.buyer_id) as all_buyers,
round((count(distinct b.buyer_id)/(count(distinct a.buyer_id),2) as repeat_buyer
from
(select
p_day,
buyer_id from buyer_trade
where p_day between '20240301' and '20240331'
group by 
p_day,
buyer_id) a
left join buyer_trade b
on a.buyer_id = b.buyer_id 
and b.p_date >a.p_date AND b.p_date <= a.p_date + 30
group by
month(a.p_day) 


 

2*len() -lenb()=把汉字的数减去/数字和字符串的数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值