假设我有这张表:
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<table>
<tr>
<th>id</th>
<th>first_date</th>
<th>second_date</th>
</tr>
<tr>
<td>1</td>
<td>2013-12-09 13:00:00</td>
<td>2013-12-09 14:00:00</td>
</tr>
<tr>
<td>2</td>
<td>2013-12-09 13:00:00</td>
<td>2013-12-10 13:00:00</td>
</tr>
<tr>
<td>3</td>
<td>2013-12-10 15:00:00</td>
<td>2013-12-10 16:00:00</td>
</tr>
</table>
对于所有行,mysql查询能否以小时为单位返回first_date和second_date之间的差值总和?我的例子是26小时? second_date将始终大于first_date。
更新: 我现在有三种方法,必须选择:
#1. My own approach of looping through each record:
records = Records.all
records.each do |r|
sum += (r.second_date-r.first_date)/1.hour
end
#2. Using inject(thanks to slowjack2k)
records = Records.all
#date_diff is a model method whick substracts the two dates and returns the result
sum = records.inject(1) {|sum, r| sum + r.date_diff }
#3. the SQL method(thanks to Shadow and slowjack2k)
sum = Records.sum('time_to_sec(timediff(second_date, first_date))')/1.hour
性能方面,他们似乎并没有多大差异。我想我会使用SQL方法。