如何在分页后对行进行求和?

时间:2013-09-10 15:26:59

标签: mysql sql

所以我有一个跟踪日历上事件的MySQL数据库。我有一个名为日历的表,其中包含与我有关的所有日期。在我的工作中,我们有合同具有一定的价值;为简化起见,我们将仅使用1和2.这些合同具有开始日期和结束日期。我想获取整个日历的所有合约,并将每天的合约价值加起来。

到目前为止,我有:

SELECT calendar.datefield AS DATE, contract.time_slots AS Slots_taken
FROM contract
RIGHT JOIN calendar ON calendar.datefield
BETWEEN contract.start_time
AND contract.end_time
LIMIT 600 , 30

这几乎给了我想要的东西。此查询生成如下表:

    DATE    |  Slots_taken
------------|--------------
2013-08-29  |     1
2013-08-30  |     1
2013-08-31  |     1
2013-09-01  |     1
2013-09-01  |     2
2013-09-02  |     1
2013-09-02  |     2
2013-09-03  |     1
2013-09-03  |     2

但是我在这里重复约会。我希望每个日期只有一行,其中包含该日期值的总和。所以它应该是:

    DATE    |  Slots_taken
------------|--------------
2013-08-29  |     1
2013-08-30  |     1
2013-08-31  |     1
2013-09-01  |     3
2013-09-02  |     3
2013-09-03  |     3

3 个答案:

答案 0 :(得分:2)

SELECT calendar.datefield AS DATE, SUM(contract.time_slots) AS Slots_taken
FROM contract
RIGHT JOIN calendar ON calendar.datefield
BETWEEN contract.start_time
AND contract.end_time
GROUP BY DATE
LIMIT 600 , 30

答案 1 :(得分:1)

如果它是普通的tSQL,我建议使用SUM()和GROUP BY:

SELECT calendar.datefield AS DATE, sum(contract.time_slots) AS Slots_taken
FROM contract
RIGHT JOIN calendar ON calendar.datefield
BETWEEN contract.start_time
AND contract.end_time
LIMIT 600 , 30
GROUP BY calendar.datefield 

禁止LIMIT,因为它不是'普通'tSQL

希望它有所帮助

修改

怎么样:

 SELECT DATE, SUM(Slots_taken) AS Slots_taken
 FROM (
   SELECT calendar.datefield AS DATE, contract.time_slots AS Slots_taken
   FROM contract
   RIGHT JOIN calendar ON calendar.datefield
   BETWEEN contract.start_time
   AND contract.end_time
   LIMIT 600 , 30) A
 GROUP BY calendar.datefield

同样,它更像是'普通'tSQL,这是一个查询的笑话:)

答案 2 :(得分:1)

SELECT calendar.datefield date
     , SUM(contract.time_slots) slots_taken
  FROM calendar
  LEFT 
  JOIN calendar 
    ON calendar.datefield BETWEEN contract.start_time AND contract.end_time
 GROUP
    BY date
 LIMIT 600 , 30;