Sql 在HAVING子句中引用
是否有方法引用AS,以便我在 有条款吗 快速解释。我的组织分为不同的业务线。我正在尝试查找组织内、整个银行内的应用程序安装总数,我希望将结果限制为仅显示业务线总数超过总数50%的应用程序 谢谢你的帮助Sql 在HAVING子句中引用,sql,sql-server,Sql,Sql Server,是否有方法引用AS,以便我在 有条款吗 快速解释。我的组织分为不同的业务线。我正在尝试查找组织内、整个银行内的应用程序安装总数,我希望将结果限制为仅显示业务线总数超过总数50%的应用程序 谢谢你的帮助 select adp_id, (select SUM(total) from dbo.IQCS_AppsByCC b where coctr_L3 = '99990001594' and b.adp_id = a.adp_id)as bl_total, (select SUM(total) fro
select adp_id,
(select SUM(total) from dbo.IQCS_AppsByCC b where coctr_L3 = '99990001594' and b.adp_id = a.adp_id)as bl_total,
(select SUM(total) from dbo.IQCS_AppsByCC c where c.adp_id = a.adp_id)as bank_total
from dbo.IQCS_AppsByCC a
where coctr_L3 = '99990001594'
and adp_id IN(19897, 15034, 17381, 13840 )
group by adp_id
HAVING bl_total / bank_total * 100 > 50
错误代码207,SQL状态S0001:列名“bl_total”无效
潜在的重复问题没有解决方案或其他解决方法,因此毫无用处。您可以使用条件聚合并使用表达式而不是别名:
select adp_id,
SUM(CASE WHEN coctr_L3 = '99990001594' THEN total ELSE 0.0 END)as bl_total,
SUM(total) as bank_total
from dbo.IQCS_AppsByCC a
where coctr_L3 = '99990001594'
and adp_id IN(19897, 15034, 17381, 13840 )
group by adp_id
HAVING
SUM(CASE WHEN coctr_L3 = '99990001594' THEN total ELSE 0 END)/SUM(total)*100>50
许多数据库在
having
子句中支持别名。您可以简化查询,也许这会起作用(可能不会):
在任何情况下,您都可以将其切换到:
having sum(case when coctr_L3 = '99990001594' then total end) > 0.5 * sum(total)
将原始查询包装到派生表中。然后,您可以在outer
WHERE
子句中使用列别名,而不是在HAVING
中使用列别名。(同样的结果。)
我认为有更好的方法
第一个和只是主和的重复
select a.adp_id, sum(total) from as bl_total, b.ttl as bank_total
from dbo.IQCS_AppsByCC a
join ( select adp_id, sum(total) as ttl
from dbo.IQCS_AppsByCC
where adp_id IN (19897, 15034, 17381, 13840)
group by adp_id
) b
on b.adp_id = a.adp_id
where coctr_L3 = '99990001594'
and a.adp_id IN (19897, 15034, 17381, 13840)
group by a.adp_id
HAVING sum(total) * 2 > b.ttl
您使用的是哪一个数据库?Microsoft SQL Server 2005第一个数据库的可能重复项而不仅仅是总和(total)?
select * from
(
select adp_id,
(select SUM(total) from dbo.IQCS_AppsByCC b where coctr_L3 = '99990001594' and b.adp_id = a.adp_id)as bl_total,
(select SUM(total) from dbo.IQCS_AppsByCC c where c.adp_id = a.adp_id)as bank_total
from dbo.IQCS_AppsByCC a
where coctr_L3 = '99990001594'
and adp_id IN(19897, 15034, 17381, 13840 )
group by adp_id
) dt
WHERE bl_total / bank_total * 100 > 50
select a.adp_id, sum(total) from as bl_total, b.ttl as bank_total
from dbo.IQCS_AppsByCC a
join ( select adp_id, sum(total) as ttl
from dbo.IQCS_AppsByCC
where adp_id IN (19897, 15034, 17381, 13840)
group by adp_id
) b
on b.adp_id = a.adp_id
where coctr_L3 = '99990001594'
and a.adp_id IN (19897, 15034, 17381, 13840)
group by a.adp_id
HAVING sum(total) * 2 > b.ttl