0

我需要从两个不同的表中获取empolyees信息employees table,以及他们的总工资。

SQL大致是这样的,但我真的不知道如何使用连接来做到这一点:

  • CONCAT(first_name, ' ', last_name) from employees as e
  • Sum(hours*pay) where date is "THIS MONTH" and employee_id = e.id from taxed_work
  • Sum(hours*pay) where date is "THIS MONTH" and employee_id = e.id from nontaxed_work

我不确定如何正确地将这些连接在一起。我不想看到本月没有完成任何一种工作的员工,只希望看到那些已经完成的员工。我正在使用 mysql 并将数据放在一个带有 php 的表中

如果有人能告诉我如何做“本月”部分,那也很酷。只是在那方面很懒惰,但在我在这里的时候想...

谢谢您的帮助!

4

3 回答 3

2

您可以使用相关的子查询:

select  concat(first_name, ' ', last_name)
,       (
        select  sum(hours*pay)
        from    taxed_work tw
        where   tw.employee_id = e.id
                and year(tw.date) = year(now())
                and month(tw.date) = month(now())
        )
,       (
        select  sum(hours*pay)
        from    nontaxed_work ntw
        where   ntw.employee_id = e.id
                and year(ntw.date) = year(now())
                and month(ntw.date) = month(now())
        )
from    employees e
于 2012-09-10T07:52:48.897 回答
0

您可以在子查询中计算它们的总数。

SELECT  a.id ,
        CONCAT(first_name, ' ', last_name) FullName,
        b.totalTax,
        c.totalNonTax,
FROM    employees a
        LEFT JOIN 
        (
            SELECT employee_id, Sum(hours*pay) totalTax
            FROM taxed_work
            WHERE DATE_FORMAT(`date`,'%c') = DATE_FORMAT(GETDATE(),'%c')
            GROUP BY employee_id
        )  b ON b.employee_id = a.id
        LEFT JOIN 
        (
            SELECT employee_id, Sum(hours*pay) totalTax
            FROM nontaxed_work
            WHERE DATE_FORMAT(`date`,'%c') = DATE_FORMAT(GETDATE(),'%c')
            GROUP BY employee_id
        ) c ON c.employee_id = a.id
于 2012-09-10T07:53:36.137 回答
0

试试这个查询。

select 
    CONCAT(first_name, ' ', last_name) as employee_name,
    sum(case when t.this_date = 'this_month' then t.hours*t.pay else 0 end), 
    sum(case when n.this_date = 'this_month' then t.hours*t.pay else 0 end) 
from employees e 
    left join taxed_work t on e.id = t.employee_id
    left join nontaxed_work n on e.id = n.employee_id
group by (first_name, ' ', last_name)

请用实际的字段名称替换 t.this_date 和 n.this_date 字段,因为我不知道确切的表结构。此外,根据您的需要替换“this_month”值。

于 2012-09-10T08:01:14.467 回答