【发布时间】:2014-04-10 01:14:18
【问题描述】:
我有 4 张桌子:
projects: id, title, current_status_id
statuses: id, label
status_history: project_id, status_id, created_at
messages: id, project_id, body, created_at
当项目在应用程序中更改状态(例如,从“lead”到“active”再到“complete”)时,插入 status_history 行。请注意 created_at 列是记录更改日期的时间戳。在状态更改之间,项目中正在发生活动并创建消息。例如,项目初始化为“lead”状态,在项目处于“lead”状态时创建一些消息,项目更改为“活动”状态,在项目处于此状态时创建一些消息,等等。
我想创建显示以下内容的查询:日期、在“领导”项目中创建的消息数、在“活动”项目中创建的消息数以及在具有其他状态的项目中创建的消息数。这可以在一个查询中完成吗?我正在使用 PostgreSQL。
这里有一些伪代码,希望能阐明我正在寻找的东西。
* Start at the earliest date
* Find all projects whose status was 'lead' on that date
* Count the number of created messages from these projects with that date
* Find all projects whose status was 'active' on that date
* Count the number of created messages from these projects with that date
* Find all projects whose status was anything else on that date
* Count the number of created messages from these projects with that date
* ... some projects change status, some stay the same, business happens ...
* Go to next date
* Find all projects whose status was 'lead' on that date
* Count the number of created messages from these projects with that date
* Find all projects whose status was 'active' on that date
* Count the number of created messages from these projects with that date
* Find all projects whose status was anything else on that date
* Count the number of created messages from these projects with that date
* ... some projects change status, some stay the same, business happens ...
* keep doing this until the present
虽然项目确实有一个 current_status_id 列,但它是当前状态,不一定是项目上个月的状态。项目的状态不会每天都在变化 - 不会每天为每个项目创建 status_history 行。
【问题讨论】:
-
如果有链接列来连接包含日期、消息、项目和状态的表,则可以创建这样的查询
-
对于给定的日期,您想要使用这些类别新创建的项目数,对吧?不是在给定日期可能已更改为其中一种状态的状态?
-
嗨,Brian,对于给定的日期,我想计算任何项目中具有特定状态的消息数量。项目的状态会随着时间而变化,因此有些消息可能是在项目处于领先地位时创建的,有些消息可能是在项目处于活动状态时发生的,等等。
标签: sql database postgresql