循环使用Fields和dateTime求和作为计数器SQL

时间:2012-11-19 08:07:07

标签: sql datetime loops

我有3个字段(ID,价格,日期) 它看起来像这样..

|ID|  |Price|    |           Date      |
--------------------------------------------
|001|  |150.00|  | 2007-01-01 11:48:18.000 |
|002|  |150.00|  | 2007-01-01 15:57:19.000 |
|003|  |150.00|  | 2007-01-02 13:26:12.000 |
|004|  |150.00|  | 2007-01-03 10:31:14.000 |

等等

我需要在一段时间内显示每天的销售总额。 所以当我把1月1日放到1月6日...... 它应该是

|   Days     |    Total Sales |
-------------------------------
| January 1  | --some amount  |
| January 2  | --some amount  |
| January 3  | --some amount  |
| January 4  | --some amount  |
| January 5  | --some amount  |
| January 6  | --some amount  |

我只是想弄明白而且我坚持使用这段代码:) ...

DECLARE @StartDate dateTime,@EndDate dateTime, @TotalSales integer

SET @StartDate = '2007-01-02 11:41:19.000' 
SET @EndDate = '2007-01-02 11:46:06.000'
SET @TotalSales = 0

while ( @StartDate = '2007-01-02 11:41:19.000' )
BEGIN

--Some codes

END

谢谢:)

2 个答案:

答案 0 :(得分:1)

您不需要循环,尽可能使用set操作:

DECLARE @StartDate dateTime,@EndDate dateTime

SET @StartDate = convert(DateTime,'2007-01-01 11:41:19.000',102)
SET @EndDate = convert(DateTime,'2007-01-04 11:46:06.000',102) 

;WITH CTE AS (
    SELECT ID,Price,[Date]  
    FROM Sales
    WHERE [Date] Between @StartDate AND @EndDate
)
SELECT DATENAME( month ,[Date] ) + ' ' + DATENAME( day ,[Date] ) AS Days
     , SUM(Price)AS 'Total Sales'
FROM CTE 
GROUP BY DATENAME( month ,[Date] ) + ' ' + DATENAME( day ,[Date] )

SQL-Fiddle Demo

答案 1 :(得分:0)

这与Tim Schmelter的解决方案类似,只是它处理没有任何销售数据的天数:

DECLARE @StartDate DATETIME, @EndDate DATETIME
SELECT @StartDate = '01-01-2007', @EndDate = '01-06-2007'

;WITH DateRange ([Date]) AS
(
    SELECT 
      @StartDate [Date]
    UNION ALL
    SELECT 
      DATEADD(DAY, 1, [Date]) [Date] 
    FROM 
      DateRange 
    WHERE 
      [Date] < @EndDate
)


SELECT 
  DATENAME(MONTH, d.[Date]) + ' ' + DATENAME(DAY, d.[Date]) AS Days,
  SUM(ISNULL(Price, 0)) AS [Total Sales]
FROM 
  DateRange d
LEFT JOIN 
  Sales s 
ON 
  d.[Date] = DATEADD(DAY, DATEDIFF(DAY, 0, s.[Date]), 0)
GROUP BY 
  DATENAME(MONTH, d.[Date]) + ' ' + DATENAME(DAY, d.[Date])

SQL Fiddle Example