我有这张桌子
+------+--------+-------------------------+
| id | amount | start_date | end_date |
| 10 | 10 | 2012-01-15 | 2012-01-20 |
| 10 | 12 | 2012-01-14 | 2012-01-15 |
| 10 | 22 | 2012-01-15 | 2012-01-16 |
+------+--------+-------------------------+
我希望找到给定间隔之间的总和。
示例:
开始日期:2012-01-13
截止日期:2012-01-18
总和(金额)= 44。
开始日期:2012-01-18
截止日期:2012-01-21
总和(金额)= 10
可以通过单个查询吗? 这有可能吗?
修改
背后的逻辑是,如果intevarls(给定一个和表内)重叠,我应该得到行。
答案 0 :(得分:3)
SELECT SUM(amount)
FROM TableX
WHERE start_date <= @EndDate
AND @StartDate <= end_date
其中@StartDate
和@EndDate
是您要检查的日期。
答案 1 :(得分:0)
SELECT SUM(AMOUNT)FROM表WHERE start_date&gt; '2012-01-13'AND_date&lt; '2012-01-18'
答案 2 :(得分:0)
当然,你可以这样做:
select sum(amount) from my_dates where start_date >= '2012-01-13' and end_date <= '2012-01-18'
给你34.如果你想得到44,你可以:
select sum(amount) from my_dates where start_date >= '2012-01-13' and end_date <= '2012-01-20'
希望这有帮助
答案 3 :(得分:0)
SELECT SUM(`amount`) as TotalAmount
FROM `tableName`
WHERE (start_date >= '2012-01-13 00:00:00'
AND
end_date <= '2012-01-18 23:59:59')