V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
irisdev
V2EX  ›  程序员

请教一个简单的 sql 语句

  •  
  •   irisdev · 2022-03-18 22:28:53 +08:00 · 1403 次点击
    这是一个创建于 763 天前的主题,其中的信息可能已经有所发展或是发生改变。

    这一题是之前的笔试做到的 有一张人员-工资表: no name salary year 1 a 8000 1999 1 a 17000 2000 2 b 9000 1998 2 b 10000 1999 3 c 10010 2000 .... 求 1999-2000 人员工资涨幅超过 8000 的员工编号 我当时是这么写的

    select s1.emp_no, (s1.salary - s2.salary) as addSalary from salaries as s1, salaries as s2 where s1.to_date like '%2000%' and s2.to_date like '%1999%' and s1.emp_no = s2.emp_no and (s1.salary - s2.salary > 8000)
    

    但是总感觉怪怪的,这应该是个挺常见的需求,一般在业务中一般怎么写,求教各位大佬(前端实习生,sql 不太会,简单勿喷)

    10 条回复    2022-03-20 14:44:42 +08:00
    shyrock
        1
    shyrock  
       2022-03-18 22:45:28 +08:00   ❤️ 1
    select name ,max(salary)-min(salary) from table
    where year in ('1999','2000')
    group by name
    having max(salary)-min(salary)>8000

    这个的问题是无法区分降薪的情况。。。
    irisdev
        2
    irisdev  
    OP
       2022-03-18 22:59:04 +08:00
    @shyrock 奥奥我当时也想到分组不过没想到咋写,感谢大佬,区分降薪那个我再想想
    wangyu17455
        3
    wangyu17455  
       2022-03-18 23:03:24 +08:00 via Android   ❤️ 1
    连表自己连自己条件是 id 相等,两张表分别记成 ab ,再加个条件 a.year=2019 and b.year=2020 然后减就行了
    ijrou
        4
    ijrou  
       2022-03-18 23:06:58 +08:00
    看题目,好难。。。
    看答案,好简单。。。
    irisdev
        5
    irisdev  
    OP
       2022-03-18 23:10:44 +08:00
    @wangyu17455
    select a.emp_no from s a inner join s b on a.id = b.id where a.year = 2019 and
    b.year = 2020 and b.salary - a.salary > 8000
    奥奥,大概写出来了,感谢!
    ration
        6
    ration  
       2022-03-18 23:25:48 +08:00   ❤️ 1
    我想复杂了。。。
    select no,sum((case when year=1999 then -1 else 1 end)*salary) from table
    where year in(1999,2000)

    group by no

    having count(1)>1 and sum((case when year=1999 then -1 else 1 end)*salary)>8000
    adoal
        7
    adoal  
       2022-03-18 23:33:46 +08:00 via iPhone   ❤️ 1
    如果不介意写 CTE ,可以 1999 和 2000 各做一张中间表,然后 JOIN
    irisdev
        8
    irisdev  
    OP
       2022-03-18 23:47:44 +08:00
    @ration 我这也算是抛砖引玉了哈哈。。
    irisdev
        9
    irisdev  
    OP
       2022-03-18 23:47:56 +08:00
    @adoal ok,我去查查 cte 是啥
    laoyb
        10
    laoyb  
       2022-03-20 14:44:42 +08:00
    其实如果较真一点的话也许该再考虑 1998->2001 这种情况的 (
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   896 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 21:09 · PVG 05:09 · LAX 14:09 · JFK 17:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.