【发布时间】:2017-05-30 09:58:59
【问题描述】:
假设是 2017 年 5 月,我想获取 2017 年 4 月的记录。
我的查询使用计数获取 2017 年 4 月的记录,但我也想包括空日期。
因此,所需的输出将是:
----------------------
id | date | count
----------------------
1 | 01/04/17 | 0 // 0 because this dates does not have any tickets.
2 | 02/04/17 | 0 // 0 because this dates does not have any tickets.
3 | 03/04/17 | 0 // 0 because this dates does not have any tickets.
4 | 04/04/17 | 0 // 0 because this dates does not have any tickets.
5 | 05/04/17 | 0 // 0 because this dates does not have any tickets.
6 | 06/04/17 | 0 // 0 because this dates does not have any tickets.
7 | 07/04/17 | 0 // 0 because this dates does not have any tickets.
8 | 08/04/17 | 0 // 0 because this dates does not have any tickets.
直到30/04/2017
15/04/17 显示 2 个计数,因为它包含 2 条记录,而我的查询也表明了这一点
但
如何从01/04/17 - 30/04/2017 开始包含空日期
查询是:
Ticket.includes(:line_items).where('tickets.created_at > ? AND
tickets.created_at < ?', Date.today.last_month.beginning_of_month,
Date.today.beginning_of_month).where.not(line_items: {id: nil}).count
输出是:
SELECT COUNT(DISTINCT "tickets"."id") FROM "tickets" LEFT OUTER JOIN
"line_items" ON "line_items"."ticket_id" = "tickets"."id" WHERE
(tickets.created_at > '2017-04-01' AND tickets.created_at < '2017-05-01') AND
("line_items"."id" IS NOT NULL)
所需的输出应显示如下记录:
同样,如果用户选择过去 7 天,它也应该显示过去 7 天的记录。
有什么办法可以解决吗?
【问题讨论】:
-
这是 pgsql 还是 mysql?
-
你的问题不清楚:你想要每天创建的票数吗?为什么你还有
line_items? -
@ŁukaszKamiński 它的 postgres
-
@coorasse
line_items用于查看工单的行项目是否存在。如果票证中包含line_items,则该票证被视为最终票证。我想计算包含 line_items 的四月每一天的票数。这有意义吗? -
如果您将问题一分为二,也许您更有可能得到答案——因为现在您正在寻找具有 pgsql 和 RoR 知识的人。您的 pgsql 问题很容易回答,我相信 RoR 部分也适合有编码经验的人。
标签: mysql ruby-on-rails postgresql ruby-on-rails-4