【问题标题】:Realm.io Query with GroupBy使用 GroupBy 查询 Realm.io
【发布时间】:2015-05-25 04:23:00
【问题描述】:
我想按月对一些帐户进行分组,我可以用 Realm.io 做到这一点吗?
public class Account extends RealmObject {
.....
private Date date;
}
RealmResults accounts = realm.where(Account.class)
.beginGroup()
.equalTo("date", "MONTH(date)")//<----- wrong code
.endGroup()
.findAll();
谢谢
【问题讨论】:
标签:
java
android
sql
orm
realm
【解决方案1】:
Realm 还不支持 GroupBy。另请注意 beginGroup() 实际上与括号相同。所以你的查询实际上被解释为:
// SQL pseudo code
SELECT * FROM Account WHERE (date = MONTH(date))
在 Realm 中,您必须执行以下操作才能选择一个月:
// Between is [ monthStart, monthEnd ]
Date monthStart = new GregorianCalendar(2015, 5, 1).getTime();
Date monthEnd = new GregorianCalendar(2015, 6, 1).getTime() - 1;
accounts = realm.where(Account.class).between("date", monthStart, monthEnd).findAll();
或类似的东西来检测一个月的变化
// pseudo code. You might want to use Calendar instead
accounts = realm.where(Account.class).findAllSorted("date")
Iterator<Account> it = accounts.iterator();
int previousMonth = it.next().getDate().getMonth();
while (it.hasNext) {
int month = it.next().getDate().getMonth();
if (month != previousMonth) {
// month changed
}
previousMonth = month;
}