1

所以我有一个 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
4

3 回答 3

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
于 2013-09-10T15:30:24.737 回答
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,这是一个查询的笑话 :)

于 2013-09-10T15:33:22.033 回答
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;
于 2013-09-10T15:41:34.967 回答