按年度查询过滤

时间:2018-01-09 19:35:52

标签: sql reporting-services

我是SQL的新手并且正在学习蹄子,我不擅长阅读书籍,所以想提出问题让我一步一步到处。对不起完整的查询不在这里因为我把笔记本电脑放在我的桌子上,但我希望有人可以指出我正确的方向。

我需要在下面添加年过滤器,以便我可以在SSRS中使用它,但每次我更改某些内容时,它仍会报告2018日期。任何帮助非常感谢

DECLARE @year date
SET @year = '20170101' --GETDATE()

--guarantee @year is Jan 01 00:00:00.
SET @year = DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0)

SELECT        Products.ProductId, Products.ProductDescription, 
              SUM(CASE WHEN SalesInvoices.EffectiveDate >= DATEADD(MONTH, 00, @year) AND 
                            SalesInvoices.EffectiveDate <  DATEADD(MONTH, 01, @year) 
                       THEN SalesInvoiceItems.Quantity ELSE 0 END) AS Jan,
              SUM(CASE WHEN SalesInvoices.EffectiveDate >= DATEADD(MONTH, 01, @year) AND 
                            SalesInvoices.EffectiveDate <  DATEADD(MONTH, 02, @year) 
                       THEN SalesInvoiceItems.Quantity ELSE 0 END) AS Feb,
              SUM(CASE WHEN SalesInvoices.EffectiveDate >= DATEADD(MONTH, 02, @year) AND 
                            SalesInvoices.EffectiveDate <  DATEADD(MONTH, 03, @year) 
                       THEN SalesInvoiceItems.Quantity ELSE 0 END) AS Mar ,
              --...
              SUM(CASE WHEN SalesInvoices.EffectiveDate >= DATEADD(MONTH, 10, @year) AND 
                            SalesInvoices.EffectiveDate <  DATEADD(MONTH, 11, @year) 
                       THEN SalesInvoiceItems.Quantity ELSE 0 END) AS Nov,
              SUM(CASE WHEN SalesInvoices.EffectiveDate >= DATEADD(MONTH, 11, @year) AND 
                            SalesInvoices.EffectiveDate <  DATEADD(MONTH, 12, @year) 
                       THEN SalesInvoiceItems.Quantity ELSE 0 END) AS Dec

FROM            SalesInvoices INNER JOIN
                             SalesInvoiceItems ON SalesInvoices.SalesInvoice = SalesInvoiceItems.SalesInvoice INNER JOIN
                             Products ON SalesInvoiceItems.Product = Products.Product

    GROUP BY      Products.ProductId, Products.ProductDescription
    --ORDER BY      ...

2 个答案:

答案 0 :(得分:0)

您可以在此处使用GETDATE()将年份设置回2018年:

SET @year = DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0)

将其更改为使用@year日期:

DECLARE @year date = '20170101'
SET @year = DATEADD(YEAR, DATEDIFF(YEAR, 0, @year), 0)

答案 1 :(得分:0)

你永远不会过于习惯养成良好的习惯(是的,我知道,这些都是意见问题)。一个这样的习惯是构建这样的日期范围查询:

where yourDateField >= @theStartOfYourDateRange
and yourDateField < the day after @theEndOfYourDateRange

除其他外,如果您的日期字段实际上是日期时间字段,则会处理时间部分。此外,您的查询将运行得更快,因为您不会按功能结果进行过滤。

查询与查询不同的细节将是您声明开始和结束日期变量的方式。为此,您不一定需要使用sql。如果应用程序代码(.net,php,coldfusion等)可用,则可能更容易使用它。