在HAVING子句中引用AS

时间:2018-03-21 20:17:19

标签: sql sql-server

有没有办法引用AS所以我可以在它中使用它们 HAVING条款?

快速解释。我的组织分为不同的业务线。我试图找到组织内整个银行的应用程序安装总数,并且我希望将结果限制为仅显示业务线总数大于总数的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) 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'。

潜在的重复问题没有解决问题的替代方法,因此无用。

4 个答案:

答案 0 :(得分:1)

将原始查询包装在派生表中。然后,您可以使用外部WHERE子句中的列别名而不是HAVING中的列别名。 (结果相同。)

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

答案 1 :(得分:1)

我认为有更好的方式 第一笔金额只是重复的主要位置

 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 

答案 2 :(得分:0)

您可以使用条件聚合并使用表达式而不是别名:

FooContainer container = new FooContainer(Arrays.asList(new Bar(), new Baz()));

JAXBContext jaxbContext = JAXBContext.newInstance(FooContainer.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(container, System.out);

答案 3 :(得分:0)

许多数据库支持having子句中的别名。您可以简化查询,也许这将起作用(它可能不会):

select adp_id,
       sum(case when coctr_L3 = '99990001594' then total end) as bl_total,
       sum(total) as bank_total
from dbo.IQCS_AppsByCC a
where adp_id in (19897, 15034, 17381, 13840)
group by adp_id
having bl_total / bank_total * 100 > 50;

在任何情况下,您都可以将其切换为:

having sum(case when coctr_L3 = '99990001594' then total end) > 0.5 * sum(total)