sql语句困难(分组和二次差)

7gs2gvoe  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(346)

我试着做一个相当困难的sqlselect语句。任何提示都非常感谢:)。链接等。以下是我的表格:

tbl_user
id     f_name       l_name    hourly_rate
1      Tom          Riddle    25
2      Frank        Smith     30
3      Lupin        Moon      35

tbl_entries
id     s_time   e_time   fk_user   fk_bank
1      08:00    10:00    1         1
2      11:05    11:50    1         2
3      12:00    18:00    2         1
4      13:00    15:00    2         1
5      10:00    12:00    3         2

tbl_bank
id     bank
1      a
2      b

我想按tbl\ U银行对它们进行选择和分组。所以我的预期结果应该是:

id (tbl_user)     f_name     l_name       bank      total time (difference)   wage
1                 Tom        Riddle       a         02:00                     50
1                 Tom        Riddle       b         00:45                     18.75  
2                 Frank      Smith        a         08:00                     240
3                 Lupin      Moon         b         02:00                     70

我有这样的东西

SELECT
    id,
    f_name,
    l_name,
    hourly_rate
FROM
    tbl_user
    INNER JOIN tbl_entries ON tbl_user.id         = tbl_entries.fk_user
    INNER JOIN tbl_bank    ON tbl_entries.fk_bank = tbl_bank.id

这给了我所有的值,但显然不是分组,没有总的时间和时间。

qrjkbowd

qrjkbowd1#

SELECT
    u.id,
    u.f_name,
    u.l_name,
    u.hourly_rate,
    ( SUM( TIMEDIFF( e.e_time, e.s_time ) / 60*60 )                 ) AS "total time (hours)",
    ( SUM( TIMEDIFF( e.e_time, e.s_time ) / 60*60 ) * u.hourly_rate ) AS wage
FROM
    tbl_user AS u
    INNER JOIN tbl_entries AS e ON u.id      = e.fk_user
    INNER JOIN tbl_bank    AS b ON e.fk_bank = b.id
GROUP BY
    u.id,
    b.id
wnvonmuf

wnvonmuf2#

您可以尝试使用timestampdiff并从那里开始执行以下操作: SELECT tu.id, tu.f_name, tu.l_name, tb.bank , TIMESTAMPDIFF(hour,CONCAT(CAST(CURDATE() AS INT),REPLACE(CONCAT(te.e_time,":00"),":","")),CONCAT(CAST(CURDATE() AS INT),REPLACE(CONCAT(te.s_time,":00"),":",""))) * tu.hourly_rate wage from tbl_entries te JOIN tbl_user tu ON (te.fk_users=tu.id) JOIN tbl_bank tb on (te.fk_bank=tb.id); 假设您的时间总是当前日期(因此curdate()在查询中),秒总是从'hh:mm:00'开始

bvn4nwqk

bvn4nwqk3#

我建议使用一个完整的datetime数据类型来表示工作班次过了午夜的时间。但这应该管用。
选择tbl\u user.id作为 id (tbl_user) ,f\ U名称,l\ U名称,银行,小时费率,时间差(e\ U时间,s\ U时间)为 total time (difference) ,(unix\u timestamp(e\u time)-unix\u timestamp(s\u time))/60/60*小时费率 wages 从tbl\u user inner join tbl\u entries on tbl\u user.id=tbl\u entries.fk\u user inner join tbl\u bank on tbl\u entries.fk\u bank=tbl\u bank.id按tbl\u user.id分组,bank;

相关问题