LeetCode 1907.按分类统计薪水

数据准备

Create table If Not Exists Accounts (account_id int, income int);
Truncate table Accounts;
insert into Accounts (account_id, income) values ('3', '108939');
insert into Accounts (account_id, income) values ('2', '12747');
insert into Accounts (account_id, income) values ('8', '87709');
insert into Accounts (account_id, income) values ('6', '91796');

需求

/*
 写出一个SQL查询,来报告每个工资类别的银行账户数量。工资类别如下:
"Low Salary":所有工资 严格低于 20000 美元。
"Average Salary": 包含 范围内的所有工资[$20000,$50000] 。
"High Salary":所有工资 严格大于 50000 美元。
结果表 必须 包含所有三个类别。如果某个类别中没有帐户,则报告0 。
 */

输入

在这里插入图片描述

输出

方法一:

with t1 as (
    select *,
       case
           when income<20000 then 'Low Salary'
           when income>50000 then 'High Salary'
           else 'Average Salary'
       end as rn1
    from Accounts
)
select rn1 as category,
       count(1) as 'accounts_count'
from t1
group by rn1
;

在这里插入图片描述
方法二:

with t1 as (
    select 'Low Salary' as category ,
       count(1) as accounts_count
    from Accounts
    where income<20000
),t2 as (
    select 'Average Salary' as category,
       coalesce(count(1),0) as accounts_count
    from Accounts
    where income>= 20000 and income<=50000
),t3 as (
    select 'High Salary' as category,
       coalesce(count(1),0) as accounts_count
    from Accounts
    where income>50000
)
select * from t1
union all
select * from t2
union all
select * from t3
;

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值