从ytd和2年前的SQL报告

时间:2013-10-10 18:27:29

标签: sql sql-server

您好我想在同一份报告中提供年度和两年前的信息的销售报告。我有这个查询作为选择2007年的例子,但我需要做年复一年,然后是2012,2011,2010。在同一份报告中。 任何的想法?感谢

我有选择,字段名称, 从表格, DocDate> ='2007-01-01'和DocDate< ='2007-12-31'

3 个答案:

答案 0 :(得分:0)

要做年份,只需将'WHERE DocDate> = 2013-01-01'

每年制作一个WHERE条件'WHERE DocDate> = 2012-01-01和DocDate< = 2012-12-12'

答案 1 :(得分:0)

CREATE PROCEDURE GetSalesReport 
    @Year AS INT
AS
BEGIN
    DECLARE @DateFrom AS DATETIME
    DECLARE @DateTo AS DATETIME

    SET @DateFrom = CONVERT(DATETIME,CONVERT(VARCHAR(4),@Year)+'0101')
    SET @DateTo = GETDATE()

    select field names 
    from tables
    where DocDate > = @DateFrom and DocDate <=@DateTo

    SET @DateFrom = CONVERT(DATETIME,CONVERT(VARCHAR(4),@Year-1)+'0101')
    SET @DateTo = CONVERT(DATETIME,CONVERT(VARCHAR(4),@Year-1)+'1231')

    select field names 
    from tables
    where DocDate > = @DateFrom and DocDate <=@DateTo


    SET @DateFrom = CONVERT(DATETIME,CONVERT(VARCHAR(4),@Year-2)+'0101')
    SET @DateTo = CONVERT(DATETIME,CONVERT(VARCHAR(4),@Year-2)+'1231')

    select field names 
    from tables
    where DocDate > = @DateFrom and DocDate <=@DateTo
END

答案 2 :(得分:0)

如果您想要当前年初至今PLUS的所有数据超过2 - 3年(标题显示2,帖子显示3)

select
      YEAR(DocDate) as EachYear,
      field names
   from 
      tables
   where 
      DocDate > = '2007-01-01'
   order by
      EachYear DESC

现在,如果您正在尝试某些聚合,例如年度销售额,总计等,您可以为&#34; EveryYear&#34;等应用GROUP BY。计算列

select
      YEAR(DocDate) as EachYear,
      sum( someTable.orderAmt ) as TotalOrdered,
      count(*) as NumberOrders,
      avg( someTable.OrderAmt ) as AvgOrder
   from 
      tables
   where 
      DocDate > = '2007-01-01'
   GROUP BY
      Year(DocDate)
   order by
      Year(DocDate) DESC