我有一个名为 xDays
的表,设置如下:
╔══════════════╦═════════════════════════╦═══════╗
║ 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
中 Hours
列的总数为 0
。在上面的例子中,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 的总小时数,其中确实显示了某些 project_names 的 0
总小时数。从这里开始,我尝试了一些不同的东西,要么得到一个
Conversion failed when converting the varchar value to datatype 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 total 转换为 int)。
我怎样才能让它正常工作?
最佳答案
您可以使用 HAVING 过滤聚合结果子句:
select sum(hours) as 'total'
From xDays
group by project_name
HAVING sum(hours) = 0
order by project_name
HAVING
子句只能出现在GROUP BY
子句之后,不能使用任何列别名
关于sql-server - 选择另一个相关列的总计为 0 的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40912206/