如何在SQL查询中添加year参数?

时间:2019-05-16 09:54:41

标签: sql parameters sql-server-2014

我要创建一个报表以使用水晶报表比较两年的销售额。我需要添加Year参数以通过在CurrentYear参数和PreviousYear参数中输入年份来过滤数据。

我在下面的查询中尝试过,但是问题是如何向聚合函数添加参数?

DECLARE @CompareYear varchar(50),
@CurrentYear varchar(50)

SELECT 
    ISNULL(sp.Telephone,'No Sales Employee'),
    od.CardCode,
    od.CardName,
    Sum(case when Year(od.DocDate)=@CompareYear then od.DocTotal else 0 end) as Sold2018,
    Sum(case when Year(od.DocDate)=@CurrentYear then od.DocTotal else 0 end) as Sold2019
FROM
    ORDR od
Left Join OSLP sp
    On od.SlpCode=sp.SlpCode
Group By
    sp.Telephone,
    od.CardCode,
    od.CardName
having(Sum(case when Year(od.DocDate)=@CompareYear then od.DocTotal else 0 end) < Sum(case when Year(od.DocDate)=@CurrentYear then od.DocTotal else 0 end))

1 个答案:

答案 0 :(得分:0)

如果我正确地实现了您的目标,则需要在YEAR(od.DocDate)GROUP BY子句上同时添加SELECT