String query = "select hour(la.dateLastUpdated) as hour,"
+ "coalesce(count(la), 0) from LoginActivity la"
+ "where la.dateLastUpdated > :date"
+ "group by hour(la.dateLastUpdated)"
+ "order by hour(la.dateLastUpdated)";
Date date = new Date(System.currentTimeMillis() - 12*60*60*1000));
我得到的结果就像是
Hour Count
---- -----
12 1
13 3
15 4
17 11
但我想要像
这样的结果Hour Count
---- -----
12 1
13 3
14 0
15 4
16 0
17 11
这意味着零计数。试过coalesce
,但它不起作用。任何可能的hql查询来获得预期的结果?原生查询也可以。
*我正在使用PostgreSql数据库
答案 0 :(得分:2)
如果您的Hour = 14
表格中不存在您想要的记录(例如LoginActivity
),您希望它如何显示在结果集中?
我假设你想列出一天中的每个小时并根据它记录记录;如果是这种情况那么
left outer join
到结果集,并加入字段Hour
。答案 1 :(得分:0)
试试这个:::
"Select hour(la.dateLastUpdated) as hour, count(coalesce(la, 0))
from LoginActivity la
where la.dateLastUpdated > :date
group by hour(la.dateLastUpdated)
order by hour(la.dateLastUpdated);"
答案 2 :(得分:0)
从postgres您可以使用此查询获得结果。
SELECT * FROM generate_series(12,24) AS s(hourdigit)
LEFT JOIN (
SELECT
hour(la.dateLastUpdated) AS hour,
coalesce(count(la), 0)
FROM LoginActivity la
WHERE la.dateLastUpdated > '2014-05-05'
GROUP BY hour(la.dateLastUpdated)
ORDER BY hour(la.dateLastUpdated)
) AS resultdata ON resultdata.hour = s.hourdigit