OrientDB - 按日期查询

时间:2016-02-06 08:15:17

标签: sql orientdb orientdb-2.1

我尝试在OrientDB中执行查询以获取每天的帖子数量。但是,我的GROUP BY查询失败了,我看不出我做错了什么。

我有一个数据库,里面有3个帖子,所有帖子都有不同的日期。

这是我的疑问:

select
    datePosted.format("dd-MM-yyyy") as day, count(*)
from
    Post
group by
    day

但是,它不起作用。我希望它能够检索每天发布帖子数量的结构,但它只检索一个结果:

[#-2:1{count:3} v0]

有什么建议吗?

1 个答案:

答案 0 :(得分:5)

我创建了这个结构,我认为这与你的结构类似:

create class Post

create property Post.datePosted date

insert into Post (datePosted) values ('2016-01-25')
insert into Post (datePosted) values ('2016-01-28')
insert into Post (datePosted) values ('2016-01-25')
insert into Post (datePosted) values ('2016-02-04')

我可以选择检索您想要的结果:

首次查询

select day, count(*) as posts from (select datePosted.format('yyyy-MM-dd') as day from Post) 
group by day

<强>输出

----+------+----------+-----
#   |@CLASS|day       |posts
----+------+----------+-----
0   |null  |2016-01-25|2
1   |null  |2016-01-28|1
2   |null  |2016-02-04|1
----+------+----------+-----

第二次查询

select datePosted.format('yyyy-MM-dd'), count(*) as posts from Post group by datePosted

<强>输出

----+------+----------+-----
#   |@CLASS|datePosted|posts
----+------+----------+-----
0   |null  |2016-01-25|2
1   |null  |2016-01-28|1
2   |null  |2016-02-04|1
----+------+----------+-----

希望有所帮助

<强> EDITED

这是Java中的一个例子:

Java代码

private static String remote = "remote:localhost/";
    public static void main(String[] args) {
        String dbName = "DBname";
        String path = remote + dbName;
        OServerAdmin serverAdmin;
        try {
            serverAdmin = new OServerAdmin(path).connect("root", "root");
            if (serverAdmin.existsDatabase()) { // if DB already exists
                System.out.println("Database '" + dbName + "' already exists");
                ODatabaseDocumentTx db = new ODatabaseDocumentTx(path);
                db.open("root", "root");
                Iterable<ODocument> results = db
                    .command(new OSQLSynchQuery<ODocument>(
                            "select day, count(*) as posts from (select datePosted.format('yyyy-MM-dd') as day from Post) group by day"))
                    .execute();
                for (ODocument result : results) {
                    System.out.println("Day: " + result.field("day") + "   Posts: " + result.field("posts"));
                }
                db.close();
            }
            else {
                serverAdmin.createDatabase(dbName, "document", "plocal");
                System.out.println("Database " + dbName + " created");
            }
            serverAdmin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

<强>输出

Day: 2016-01-25   Posts: 2
Day: 2016-01-28   Posts: 1
Day: 2016-02-04   Posts: 1