SQL Server查询Have子句

时间:2018-09-17 11:48:11

标签: sql sql-server having-clause

在下面的查询中,#'子句之后出现错误。任何帮助将不胜感激。预先感谢。

HAVING

3 个答案:

答案 0 :(得分:2)

SQL Server要求您在HAVING子句中重复该表达式(或使用CTE或子查询)。您没有聚合功能,所以我想您打算这样做:

select round(sum(TaxableAmount), 0) as t,
       round(sum(TaxValue*100/TaxPercentage), 0) as t2
from VoucherTaxDetail
where TaxPercentage <> 0 and TaxableAmount > 0 and
      TableName in ('TVPayment', 'Payment')
group by transactionId
having round(sum(TaxableAmount), 0) <> round(sum(TaxValue*100/TaxPercentage), 0);

答案 1 :(得分:1)

您不能在HAVING子句中使用列别名。诀窍是将查询包装为派生表(子查询)。然后,您可以在外部WHERE子句中使用这些别名。

select *
from
(
    select round(TaxableAmount,0) as t, round(((TaxValue*100)/TaxPercentage),0)as t2
    from VoucherTaxDetail 
    where  TaxPercentage<>0 and TaxableAmount>0 and TableName in('TVPayment','Payment')
    group by transactionId
) dt
where t<>t2

答案 2 :(得分:0)

但是,我为我的查询找到了这个答案。我只是想到使用带有WITH子句和CTE的内部查询的输出。 基本上,我了解到我们不能在HAVING子句中使用别名的输出来应用条件。

 with cte as (
 Select round(TaxableAmount,0) as t,
 round(((TaxValue*100)/TaxPercentage),0)as t2 
 from VoucherTaxDetail where
 TaxPercentage<>0 and TaxableAmount>0 and TableName in('TVPayment','Payment'))
 select * from cte where t<>t2