0

I need to get sales comparison between two reporting periods. It should display sales which only have decreased than previous year. I tried below query to get values.But how can I add aggregate function in where clause.

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
4

3 回答 3

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
于 2019-05-16T06:31:02.990 回答
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
于 2019-05-16T07:17:07.570 回答
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))
于 2019-05-16T06:32:22.350 回答