根据列的总和返回最小值和最大值
Posted
技术标签:
【中文标题】根据列的总和返回最小值和最大值【英文标题】:Returning min and max based on sum of column 【发布时间】:2019-07-19 14:50:03 【问题描述】:我有一张表Employees
,列有:day
、employeeid
、earned
、hourofday
。所以我有不同的行,例如:
day | employeeid | earned | hourofday
25/01/2019 | 422 | 50 | 14
25/01/2019 | 422 | 60 | 15
25/01/2019 | 422 | 40 | 16
我想知道哪个员工每天的最低和最高总收入?
到目前为止,我已经设法返回了总收入/小时数:
SELECT day, employeeid, SUM(earned_that_hour) as earned_that_day FROM Employees GROUP BY day, employeeid
然后我尝试在earned_that_day
列上使用 MAX() 和 MIN():
SELECT day, campaignid, MAX(earned_that_day), MIN(earned_that_day)
FROM (SELECT day, employeeid, SUM(earned_that_hour) as earned_that_day FROM Employees GROUP BY day, employeeid)
GROUP BY day, employeeid
但是 MAX 和 MIN 列都返回总和,而不是每天 &employeeid 的最小值和最大值。如何修改查询以返回?我现在有 4 天
【问题讨论】:
python相关性在哪里? 我猜没有,但我用的是sqlite,已编辑 【参考方案1】:使用 2 个 CTE,获取每位员工每天的总和以及每天的最大值/最小值。 然后加入他们:
WITH
cte AS (
SELECT day, employeeid, SUM(earned_that_hour) as earned_that_day
FROM Employees
GROUP BY day, employeeid
),
maxmin AS (
SELECT day, MIN(earned_that_day) minearned, MAX(earned_that_day) maxearned
FROM cte
GROUP BY day
)
SELECT c.*
FROM cte c inner join maxmin m
ON m.day = c.day AND (c.earned_that_day IN (m.minearned, m.maxearned))
ORDER BY c.day, c.earned_that_day
【讨论】:
这会返回部分正确的结果。我有跨越 4 个不同日子的数据。前 3 天它确实每天返回 2 行,即当天收入最多的员工 ID 和当天收入最少的员工 ID,但在最后一天它返回 10 行:当天收入的最大值和员工 ID,以及然后是 9 个不同的行,其中员工收入为 0 如果有超过 1 名员工的最低要求,您希望退回什么? 转念一想,这个结果还不错!我知道他们在赚=0时都是平等的。非常感谢【参考方案2】:在较新版本的 SQLite 中,您可以使用窗口函数:
SELECT e.*
FROM (SELECT day, employeeid, SUM(earned_that_hour) as earned_that_day,
MIN(SUM(earned_that_hour)) OVER (PARTITION BY DAY) as day_min,
MAX(SUM(earned_that_hour)) OVER (PARTITION BY DAY) as day_max
FROM Employees e
GROUP BY day, employeeid
) e
WHERE earned_that_day IN (day_min, day_max)
ORDER BY day;
【讨论】:
我收到sqlite3.OperationalError: no such table: e
您是否在为您的员工表起别名?以上是关于根据列的总和返回最小值和最大值的主要内容,如果未能解决你的问题,请参考以下文章