2016-12-01 48 views
2

我有一个表叫xDays设置如下图所示:选择列,其中另一列相关的总数为0

╔══════════════╦═════════════════════════╦═══════╗ 
║ Project_Name ║   Date   ║ Hours ║ 
╠══════════════╬═════════════════════════╬═══════╣ 
║ proj1  ║ 2010-03-03 00:00:00.000 ║  0 ║ 
║ proj1  ║ 2010-03-04 00:00:00.000 ║  0 ║ 
║ proj1  ║ 2010-03-05 00:00:00.000 ║  0 ║ 
║ proj2  ║ 2010-03-03 00:00:00.000 ║  1 ║ 
║ proj2  ║ 2010-03-04 00:00:00.000 ║  0 ║ 
║ proj2  ║ 2010-03-05 00:00:00.000 ║  0 ║ 
╚══════════════╩═════════════════════════╩═══════╝ 

我试图做的是选择每个Project_Name谁是总在Hours0。在上面的例子中,SELECT语句应该返回proj1,因为它总hours为0,而对于proj2总课时为1

我得到的最接近是:

select sum(hours) as 'total', project_name 
From xDays 
group by project_name 
order by project_name 

这给了我一个表格显示每个project_name的总小时数,它显示0某些project_names的总小时数。从这里,我已经尝试了一些不同的东西,要么得到一个

转换转换为varchar值定义了int类型

错误或空结果时失败。我试过的一些例子:

select sum(hours) as 'total', project_name 
From xDays 
where 'total' = convert(varchar(10), 0) 
group by project_name 
order by project_name` 

这会返回空结果。

select sum(hours) as 'total', project_name 
From xDays 
where 'total' = 0 
group by project_name 
order by project_name 

这会返回转换错误(无法将varchar转换为int)。

我如何才能正常工作?

+0

如果所有项目都不应该出现在提取中,那么所有项目在'xDays'表中是否都有条目?是否有可能将负小时分配给项目? – JohnLBevan

+0

无负面小时。 – pfinferno

+1

注意:'where'total'= 0'这里你将字符串值'total'(不是列/结果)与0进行比较。 – JohnLBevan

回答

4

您可以用HAVING条款筛选汇总结果:

select sum(hours) as 'total' 
From xDays 
group by project_name 
HAVING sum(hours) = 0 
order by project_name 

HAVING子句只能出现在GROUP BY条款后,不能使用任何列别名

2

请尝试以下

Select Project_Name 
From xDays 
Group By Project_Name 
Having Sum(Hours)=0 
1

试试这个:

select project_name 
from xDays 
group by project_name 
having sum(xdays.hours) = 0 

您将需要利用THA having条款过滤器的基础上累计总额

2

假设你想要回报都在xDays表中的所有项目,@PanagiotisKanavos's answer最好的。

特殊场景/注意事项

如果它可能具有不具备在xDays表中的任何条目的项目,但仍希望那些返回(即,因为在该表不是它的暗示没有花费在他们身上)。

select project_name 
from Projects 
where project_name not in 
(
    select distinct project_name 
    from xDays 
    where xdays.hours != 0 
) 

如果可能有负小时数,并且您希望那些项目的总小时数等于零的项目(即,其中负片取消正片):

select project_name 
from Projects 
where project_name not in 
(
    select project_name 
    from xDays 
    group by project_name 
    having sum(xdays.hours) != 0 
) 
+1

感谢你们,我实际上有一个单独的select语句,在xDays表中有条目,但可以使用第一条语句将它们组合在一起。 – pfinferno

相关问题