我有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_DATE
子句中添加新字段WHERE
以限制项目数量,仅限于在该时间间隔内创建的某些项目任务。所以我用表inner join project_task
进行INNER JOIN并且结果应该更小但是我得到的结果是这些巨大的数字。不知道如何组合它。
感谢您的帮助
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。
所以我必须以某种方式限制这些值,而不是我
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
您的加入表project_task可能在“project_id”列中有重复项