给定时间间隔

时间:2016-06-29 19:53:22

标签: sql-server

我有以下MS SQL Server查询在特定日期(2016-06-22)返回SUM:

SELECT SUM(Value) FROM Sales 
WHERE EndDate>='2016-06-22' AND StartDate<'2016-06-22'

我正在尝试显示所选间隔的每一天的SUM。

我想要的就是这样:

SELECT
  (SELECT SUM(Value) FROM Sales WHERE EndDate>='2016-06-01' AND StartDate<'2016-06-01'), 
  (SELECT SUM(Value) FROM Sales WHERE EndDate>='2016-06-02' AND StartDate<'2016-06-02'),
  .... 
  (SELECT SUM(Value) FROM Sales WHERE EndDate>='2016-06-30' AND StartDate<'2016-06-30')

我希望以更优雅的方式完成它。

2 个答案:

答案 0 :(得分:0)

您可以按startdate或enddate进行分组。这假设您的startdate或enddate是唯一相关的日期字段,而不是两者。但如果您的销售数据跨越多天,则可以对其进行调整。

例如:

SELECT enddate,SUM(Value) FROM Sales WHERE EndDate>='2016-01-01' AND StartDate<'2016-1-03'
GROUP BY enddate

答案 1 :(得分:0)

我使用UDF创建动态日期范围(如下所示)。您也可以使用Numbers或Tally表

Select DateR1
      ,SomeTotal = sum(Value)
 From  Aales A
 Join (Select DateR1=RetVal,DateR2=DateAdd(DD,1,RetVal) from [dbo].[udf-Create-Range-Date]('2016-06-01','2016-06-30','DD',1)) B
   on  SalesDate Between DateR1 and DateR2 and SalesDate<DateR2
 Group By DateR1
 Order By DateR1

UDF

CREATE FUNCTION [dbo].[udf-Create-Range-Date] (@DateFrom datetime,@DateTo datetime,@DatePart varchar(10),@Incr int)

Returns 
@ReturnVal Table (RetVal datetime)

As
Begin
    With DateTable As (
        Select DateFrom = @DateFrom
        Union All
        Select Case @DatePart
               When 'YY' then DateAdd(YY, @Incr, df.dateFrom)
               When 'QQ' then DateAdd(QQ, @Incr, df.dateFrom)
               When 'MM' then DateAdd(MM, @Incr, df.dateFrom)
               When 'WK' then DateAdd(WK, @Incr, df.dateFrom)
               When 'DD' then DateAdd(DD, @Incr, df.dateFrom)
               When 'HH' then DateAdd(HH, @Incr, df.dateFrom)
               When 'MI' then DateAdd(MI, @Incr, df.dateFrom)
               When 'SS' then DateAdd(SS, @Incr, df.dateFrom)
               End
        From DateTable DF
        Where DF.DateFrom < @DateTo
    )

    Insert into @ReturnVal(RetVal) Select DateFrom From DateTable option (maxrecursion 32767)

    Return
End

-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2020-10-01','YY',1) 
-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2020-10-01','DD',1) 
-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2016-10-31','MI',15) 
-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2016-10-02','SS',1)