如何在where子句中添加聚合函数值?

时间:2019-05-16 06:26:37

标签: sql sql-server-2014

我需要在两个报告期之间进行销售比较。它应该显示仅比上一年下降的销售额。我尝试在下面的查询中获取值。但是如何在where子句中添加聚合函数。

SELECT 
CardCode,
CardName,
Sum(case when Year(DocDate)='2018' then DocTotal else 0 end) as Sold2018,
Sum(case when Year(DocDate)='2019' then DocTotal else 0 end) as Sold2019
FROM
ORDR
***where Sold2018 < Sold2019***
Group By
CardCode,
CardName

3 个答案:

答案 0 :(得分:3)

使用having子句:

SELECT 
  CardCode,
  CardName,
  Sum(case when Year(DocDate)='2018' then DocTotal else 0 end) as Sold2018,
  Sum(case when Year(DocDate)='2019' then DocTotal else 0 end) as Sold2019
FROM ORDR
Group By CardCode, CardName
having Sum(case when Year(DocDate)='2018' then DocTotal else 0 end) < Sum(case when Year(DocDate)='2019' then DocTotal else 0 end)

或使用子查询和where子句:

select *
from (
    SELECT 
      CardCode,
      CardName,
      Sum(case when Year(DocDate)='2018' then DocTotal else 0 end) as Sold2018,
      Sum(case when Year(DocDate)='2019' then DocTotal else 0 end) as Sold2019
    FROM ORDR
    Group By CardCode, CardName
) where Sold2018 < Sold2019

答案 1 :(得分:0)

只需使用HAVING,如下所示:

SELECT 
    CardCode,
    CardName,
    Sum(case when Year(DocDate)='2018' then DocTotal else 0 end) as Sold2018,
    Sum(case when Year(DocDate)='2019' then DocTotal else 0 end) as Sold2019
FROM
    ORDR
Group By
    CardCode,
    CardName
having(Sum(case when Year(DocDate)='2018' then DocTotal else 0 end) < Sum(case when Year(DocDate)='2019' then DocTotal else 0 end))

答案 2 :(得分:0)

您可以将具有作为 Shawn.X 的响应。使用通用表和where子句可以使查询的可读性更高。

with totalOf2018 as (
select  CardCode, CardName, Sum(DocTotal) as Sold2018,
from  ORDR   
where Year(DocDate)='2018'
Group By CardCode, CardName
), totalOf2019 as(
select  CardCode, CardName, Sum(DocTotal) as Sold2019,
from  ORDR   
where Year(DocDate)='2019'
Group By CardCode, CardName
)
select 
a.CardCode, a.CardName, a.Sold2018, b.Sold2019
from totalOf2018 a
join totalOf2019  b on a.CardCode = b.CardCode and a.CardName = b.CardName
where a.Sold2018 < b.Sold2019