SQL面试题挑战10:累计占比

目录

问题:

现在有一张每个年份的每个部门的收入表。现在需要算每个部门的收入占同类型部门的收入的占比和当年整个公司的收入占比。要求一条SQL计算出来。比如研发部和产品部属于同类型的,都是产研;财务部和人事部都属于职能。

powershell 复制代码
year    dept    income
2023    研发部    5000
2023    产品部    6000
2023    财务部    7000
2023    人事部    8000
2022    研发部    10000
2022    产品部    8000
2022    财务部    9000
2022   人事部    8000

SQL解答:

考察sum() over 开窗函数的使用。

sql 复制代码
with temp as
(
    select '2023' as year,"研发部" as dept,5000 as income
    union all
    select '2023' as year,"产品部" as dept,6000 as income
    union all
    select '2023' as year,"财务部" as dept,7000 as income
    union all
    select '2023' as year,"人事部" as dept,8000 as income
    union all 
    select '2022' as year,"研发部" as dept,10000 as income
    union all
    select '2022' as year,"产品部" as dept,8000 as income
    union all
    select '2022' as year,"财务部" as dept,9000 as income
    union all
    select '2022' as year,"人事部" as dept,8000 as income
)
select
year
,dept
,income
,round(income/similar_dept_income,2) as similar_dept_income_rate
,round(income/year_income,2) as year_income_rate
from
(
    select
    year
    ,dept
    ,income
    ,sum(income) over(partition by year,case 
                        when dept in("研发部","产品部") then "产研"
                        when dept in("财务部","人事部") then "职能"
                        end
    ) as similar_dept_income  --同类型部门收入
    ,sum(income) over(partition by year) as year_income
    from temp
) t1
;
----结果为:
序号       year      dept       income     similar_dept_income_rate     year_income_rate
1	       2022     研发部      10000              0.56                      0.29
2	       2022     产品部      8000               0.44                      0.23
3	       2022     财务部      9000               0.53                      0.26
4	       2022     人事部      8000               0.47                      0.23
5	       2023     研发部      5000               0.45                      0.19
6	       2023     产品部      6000               0.55                      0.23
7	       2023     财务部      7000               0.47                      0.27
8          2023     人事部      8000               0.53                      0.31
相关推荐
幽灵诶1 小时前
Mysql(基于测试的学习)
数据库·mysql
砚底藏山河1 小时前
python量化自定义周期 K 线合成
java·开发语言·数据库·python·金融
宇宙无敌暴龙战士6661 小时前
MySQL 8 库表操作学习笔记:SQL 基础、库表管理、约束与用户授权全流程
数据库·sql·mysql·学习笔记·后端开发
猿究院_夏燊2 小时前
MySQL 的四种隔离级别
java·数据库·mysql
say_fall2 小时前
【Linux系统编程】Ext 文件系统:磁盘与存储、文件与目录、现代计算机究竟如何寻找文件
linux·运维·服务器·数据库·c++
共享家95273 小时前
408 操作系统第一章
服务器·数据库·windows
这个DBA有点耶3 小时前
连拿六年第一后宣布出海:国产数据库凭什么敢撕掉“平替”的标签?
数据库·人工智能·架构
云和恩墨4 小时前
数据库监控简史:从会回答到能交付——AI-DBA如何成为真正的数字同事
数据库·人工智能·dba
这个DBA有点耶4 小时前
为什么删掉索引后,查询瞬间变快了?探讨MySQL的随机I/O与顺序I/O博弈
数据库·mysql·代码规范
kingx35 小时前
BugKu 渗透测试 4 实战:文件上传打点,5 Flag 全通
数据库·渗透测试·web·内网渗透