我有2张桌子:
员工:
e_id | firstname | lastname
-------+-----------+-----------
10100 | Mark | Stevens
10101 | Alex | Watts
10102 | Hannah | Burton
和works_on:
employee_e_id | product_prod_nr | hours
---------------+-----------------+-------
10100 | 66000 | 40
10100 | 77211 | 37
10101 | 90210 | 67
我现在想获取工作时间最少的人的e_id,名字,姓氏和工作时间。这只是来自两个表的示例数据。 我尝试将其限制为1,但是例如当我有2个人工作1小时时,该方法将不起作用。
答案 0 :(得分:0)
尝试使用窗口功能,如下所示
with cte as
(
select e.e_id,
e.firstname,e.lastname,w.hours,row_number() over(order by w.hours asc) rn
from eomployee e join works_on w on e.e_id=w.employee_e_id
) select * from cte where rn=1
答案 1 :(得分:0)
如果您要使行数最少(在示例中为37):
SELECT
e.e_id,
e.firstname,
e.lastname,
w.hours
FROM
eomployee e
JOIN works_on w ON e.e_id = w.employee_e_id
ORDER BY w.hours
LIMIT 1
如果您要获得该行的累计工作时间(在您的示例中,“ 10100”的工作时间为37+ 40 = 77小时):
SELECT
e_Id, firstname, lastname, hours
FROM (
SELECT
e.e_id,
e.firstname,
e.lastname,
w.hours,
SUM(hours) OVER (PARTITION BY e_id) as cum
FROM
eomployee e
JOIN works_on w ON e.e_id = w.employee_e_id
) s
ORDER BY cum
LIMIT 1
答案 2 :(得分:0)
尝试一下:
val1=1
val2=2
val3=3
tab1_0=table1 0
tab1_1=table1 1
tab1_2=table1 2
tab2_0=undefined
tab2_1=undefined
tab2_2=undefined
tab2_3=undefined
tab2_4=undefined
答案 3 :(得分:0)
您可以使用窗口功能:
SELECT e_Id, firstname, lastname, hours
FROM (SELECT e.*,
MIN(hours) OVER () as min_hours
FROM eomployee e JOIN
works_on w
ON e.e_id = w.employee_e_id
) ew
WHERE hours = min_hours;