duangang3832 2014-01-28 22:13
浏览 15
已采纳

从多个表中进行选择,并将1个表中的所有匹配项相加

I have two tables, one with an accountID, hours, and date columns and the other with accountID, minutes, and date columns. The first table will only ever have 1 entry for each date but the second could have multiple. What I want to do is select everything from both tables where the accountID's match up, but add up the minutes of each occurrence in the second table.

I apologize if this makes no sense. Here's an example:

Table1:

Account ID | hours | date
1             4       2014-1-1
1             3       2014-1-2
2             2       2014-1-3
3             3       2014-1-3

Table2:

Account ID | minutes | date
1            34        2014-1-1
1            36        2014-1-1
1            32        2014-1-2
1            12        2014-1-2

I don't want more than 1 row per day so the minutes for Jan 1 and Jan 2 need to be combined, is this possible?

EDIT: I want the hours from table 1 and the summation of the minutes by date from table 2. So on Jan 1 minutes would be 70 and hours would be 4.

  • 写回答

2条回答 默认 最新

  • doubu1950 2014-01-28 22:32
    关注

    What you want is a group by clause on a table join. In this case you'll need a double group by since you want id, date pairings. You'll have to sum the hours even though you indicated they are unique to account ids to prevent the grouping clause from complaining.

    SELECT `Account ID`, `date`, SUM(`hours`) AS `hours`, SUM(`minutes`) AS `minutes`
    FROM `table1` 
    JOIN `table2` ON (`table1`.`Account ID` = `table2`.`Account ID` AND `table1`.`date` = `table2`.`date`)
    GROUP BY `Account ID`, `date`;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?