2

我有返回正确结果的 SQL。

select accounts.name, count( case when ((( estimated_start_date<='2013-01-01' 
and project.status='closed')

or ( estimated_start_date<='2013-01-01' and project.status='open' 
and estimated_end_date>='2013-04-01')))
then 1 else null end) as Number

from project

inner join project_cstm on project.id=project_cstm.id_c
inner join accounts on project_cstm.account_id_c=accounts.id

group by accounts.name

我给了我很好的结果:

例如:

Telenor 5
Telecom 3

现在我想BOOKED_DATEWHERE子句中添加新字段以限制项目数量,仅在该时间间隔内创建一些项目任务。所以我用表做 INNER JOIN,inner join project_task结果应该更小,但结果却是我得到了这些巨大的数字。不知道如何组合它。

感谢帮助

Telenor 150
Telecom 980

select accounts.name, count( case when ((( estimated_start_date<='2013-01-01' 
and project.status='closed')

or ( estimated_start_date<='2013-01-01' and project.status='open' 
and estimated_end_date>='2013-04-01')))
then 1 else null end) as Number

from project

inner join project_cstm on project.id=project_cstm.id_c
inner join accounts on project_cstm.account_id_c=accounts.id
inner join project_task on project_task.project_id=project.id
where booked_date>'2013-01-01' and booked_date<'2015-01-01'
group by accounts.name

由于表 PROJECT_TASK 中的行,我得到的结果远非正确。如何限制它?我试过推杆,... count(distinct case when ...但结果总是 1。

所以我必须以某种方式限制这个值,而不是我

4

3 回答 3

2

您为项目的每个任务计算 1,这就是为什么您有这么多。
对于每个项目,您只需将计数增加 1 次。

您想计算不同的项目,因此不要只计算 1,而是计算不同的项目 id:

select accounts.name
     , count( distinct  -- here distinct
        case when ((( estimated_start_date<='2013-01-01' and project.status='closed')
                 or ( estimated_start_date<='2013-01-01' and project.status='open' and estimated_end_date>='2013-04-01')))
        then project.id -- here project id
        else null 
        end) as Number
from project
    inner join project_cstm 
        on project.id=project_cstm.id_c
    inner join accounts 
        on project_cstm.account_id_c=accounts.id
    inner join project_task 
        on project_task.project_id=project.id
where booked_date>'2013-01-01' 
and booked_date<'2015-01-01'
group by accounts.name
于 2013-04-12T12:19:23.460 回答
0

我无法测试您的查询,但我认为您应该使用以下内容:

select accounts.name, count(DISTINCT project.id) as Number
from project   
  inner join project_cstm on project.id=project_cstm.id_c
  inner join accounts on project_cstm.account_id_c=accounts.id
  inner join project_task on project_task.project_id=project.id
where
  (booked_date>'2013-01-01' and booked_date<'2015-01-01')
  AND ((estimated_start_date<='2013-01-01' and project.status='closed')
      OR
       (estimated_start_date<='2013-01-01'
        and project.status='open'
        and estimated_end_date>='2013-04-01'))
group by accounts.name
于 2013-04-12T12:18:53.207 回答
0

您的加入表 project_task 可能在“project_id”列中有重复项

于 2013-04-12T12:23:42.857 回答