根据列的总和返回最小值和最大值

时间:2019-07-19 14:50:03

标签: sql sqlite

我有一个表(a >= 1.).cumsum(axis=1, dtype=bool).view('i1') array([[0, 0, 0, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 1, 1]], dtype=int32) ,其列为:Employeesdayemployeeidearned。所以我有不同的行,例如:

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列上使用MAX()和MIN():

earned_that_day

但是MAX和MIN列都返回总和,而不是每天和雇员的最小值和最大值。如何修改查询以返回?我目前有4天

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

在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;