2014-02-11 111 views
0

我希望根據檢索UserProfile註冊列表。 域對象UserProfile存儲Date creationDate屬性。 我試過Gorm count elements group by day day time

def results = UserProfile.executeQuery('select u.creationDate, count(u) from UserProfile as u group by u.creationDate') 
println results 

這顯然不是我所需要的,因爲數據是(已經)存儲在它完成時間。

任何資源精明的解決方案將適用於:預測,HQL,...

Thnks

回答

2

我用HQL投功能:

def results = UserProfile.executeQuery(""" 
    select cast(u.creationDate as date), count(u) 
    from UserProfile as u 
    group by cast(u.creationDate as date) 
""") 

基礎數據庫必須支持ANSI投(...爲...)語法這個工作,這是一個針對PostgreSQL,MySQL和甲骨文,SQL的情況下服務器和許多其他數據庫管理系統

0

打破日期daymonthyear則忽略該項timestamp

這應該給你你需要的東西。

def query = 
""" 
select new map(day(u.creationDate) as day, 
       month(u.creationDate) as month, 
       year(u.creationDate) as year, 
       count(u) as count) 
     from UserProfile as u 
     group by day(u.creationDate), 
       month(u.creationDate), 
       year(u.creationDate) 
""" 

//If you do not worry about dates any more then this should be enough 
def results = UserProfile.executeQuery(query) 

//Or create date string which can be parsed later 
def refinedresults = 
    results.collect { [ "$it.year-$it.month-$it.day" : it.count ] } 

//Or parse it right here 
def refinedresults = 
    results.collect { 
     [ Date.parse('yyyy-MM-dd', "$it.year-$it.month-$it.day") : it.count ] 
    } 
0

您可以將"derived" property定義爲一個公式,以提取日期和時間的日期部分。確切的配方會根據你所使用的數據庫,MySQL的,你可以使用類似

Date creationDay // not sure exactly what type this needs to be, it may need 
       // to be java.sql.Date instead of java.util.Date 

static mapping = { 
    creationDay formula: 'DATE(creation_date)' 
} 

(公式使用DB列名,而不是格姆屬性名稱)不同。現在你可以通過creationDay而不是creationDate進行分組,它應該可以滿足你的需求。

或者不用「日期」,您可以在其他答案中建議的年,月,日使用不同的字段,我認爲這些函數在H2和MySQL中都是有效的。

+0

依賴方言是我不考慮此選項的原因。你是對的。 :) – dmahapatro