gpt4 book ai didi

mysql - 我将如何返回 SQL 数学运算的结果?

转载 作者:可可西里 更新时间:2023-11-01 07:25:15 28 4
gpt4 key购买 nike

所以我最近参加了一些更高级别的 SQL 问题的测试。我在 SQL 方面只有我认为的“中级”经验,而且我已经为此工作了一天左右。我就是想不通。


问题是:

您有一个包含 4 列的表格:

EmployeeID     int unique
EmployeeType int
EmployeeSalary int
Created date

目标: 我需要检索任何超过 1 个条目的 EmployeeType 的最新两个 EmployeeSalary 之间的差异。它必须在一个语句中完成(嵌套查询很好)。


示例数据集:http://sqlfiddle.com/#!9/0dfc7

EmployeeID | EmployeeType | EmployeeSalary | Created
-----------|--------------|----------------|--------------------
1 | 53 | 50 | 2015-11-15 00:00:00
2 | 66 | 20 | 2014-11-11 04:20:23
3 | 66 | 30 | 2015-11-03 08:26:21
4 | 66 | 10 | 2013-11-02 11:32:47
5 | 78 | 70 | 2009-11-08 04:47:47
6 | 78 | 45 | 2006-11-01 04:42:55

所以对于这个数据集,正确的返回是:

EmployeeType | EmployeeSalary 
-------------|---------------
66 | 10
78 | 25

10 来自 EmployeeType 为 66 的最新两个 EmployeeSalary 值 (30 - 20) 相减。25 来自 EmployeeType 为 78 的最新两个 EmployeeSalary 值 (70-45) 相减。我们完全跳过 EmployeeID 53,因为它只有一个值。

这个一直在摧毁我的大脑。有什么线索吗?

谢谢!

最佳答案

如何使非常简单的查询变得复杂?

一种有趣的方式(不是最佳性能)是:

SELECT final.EmployeeType, SUM(salary) AS difference
FROM (
SELECT b.EmployeeType, b.EmployeeSalary AS salary
FROM tab b
JOIN (SELECT EmployeeType, GROUP_CONCAT(EmployeeSalary ORDER BY Created DESC) AS c
FROM tab
GROUP BY EmployeeType
HAVING COUNT(*) > 1) AS sub
ON b.EmployeeType = sub.EmployeeType
AND FIND_IN_SET(b.EmployeeSalary, sub.c) = 1
UNION ALL
SELECT b.EmployeeType, -b.EmployeeSalary AS salary
FROM tab b
JOIN (SELECT EmployeeType, GROUP_CONCAT(EmployeeSalary ORDER BY Created DESC) AS c
FROM tab
GROUP BY EmployeeType
HAVING COUNT(*) > 1) AS sub
ON b.EmployeeType = sub.EmployeeType
AND FIND_IN_SET(b.EmployeeSalary, sub.c) = 2
) AS final
GROUP BY final.EmployeeType;

SqlFiddleDemo

编辑:

关键是 MySQL 不支持窗口函数,因此您需要使用等效代码:

例如 SQL Server 中的解决方案:

SELECT EmployeeType, SUM(CASE rn WHEN 1 THEN EmployeeSalary 
ELSE -EmployeeSalary END) AS difference
FROM (SELECT *,
ROW_NUMBER() OVER(PARTITION BY EmployeeType ORDER BY Created DESC) AS rn
FROM #tab
) AS sub
WHERE rn IN (1,2)
GROUP BY EmployeeType
HAVING COUNT(EmployeeType) > 1

LiveDemo

MySQL 等效:

SELECT EmployeeType, SUM(CASE rn WHEN 1 THEN EmployeeSalary 
ELSE -EmployeeSalary END) AS difference
FROM (
SELECT t1.EmployeeType, t1.EmployeeSalary,
count(t2.Created) + 1 as rn
FROM #tab t1
LEFT JOIN #tab t2
ON t1.EmployeeType = t2.EmployeeType
AND t1.Created < t2.Created
GROUP BY t1.EmployeeType, t1.EmployeeSalary
) AS sub
WHERE rn IN (1,2)
GROUP BY EmployeeType
HAVING COUNT(EmployeeType) > 1;

LiveDemo2

关于mysql - 我将如何返回 SQL 数学运算的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33877389/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com