在sql server中过去7天的最佳方法?

时间:2011-12-08 15:28:56

标签: sql-server sql-server-2005 sql-server-2008 tsql

我需要过去24小时,7天的结果。我想要的结果需要采用以下格式:

2011-11-05   11 orders  $12354.94
2011-11-04   12 orders  $12555.72
2011-11-03   5 orders  $1000.24

在尝试一些查询时,我不断返回不同的行数。例如,此查询:

SELECT CAST(Left(OrderDate,10) as smalldatetime) as PurchaseDate,
       COUNT(Orders.WebOrderNumber) as "Rows",
       SUM(cast(Orders.Total_Lines_Net AS money)) as Total
FROM Orders 
WHERE OrderDate  BETWEEN getdate() - 7 AND getdate() 
GROUP BY cast(Left(OrderDate,10) as smalldatetime)
ORDER BY cast(Left(OrderDate,10) as smalldatetime)

返回此数据:

   PurchaseDate Rows    Total
2011-12-01 00:00:00 1539    404798.85
2011-12-02 00:00:00 1572    324963.604
2011-12-03 00:00:00 970 119244.93
2011-12-04 00:00:00 1092    120888.244
2011-12-05 00:00:00 1201    337646.952
2011-12-06 00:00:00 1309    287609.243
2011-12-07 00:00:00 1555    315223.22

我认为12月1日的行似乎很低,所以我尝试了另一个查询:

SELECT   SUM(cast(Orders.Total_Lines_Net AS money)) as Total,
         COUNT(Orders.WebOrderNumber) as "Rows",
         CAST(Left(OrderDate,10) as smalldatetime) as PurchaseDate
FROM Orders 
WHERE OrderDate between '2011-12-01 00:00:00' AND  + '2011-12-01 23:59:59'
GROUP BY cast(Left(OrderDate,10) as smalldatetime)

返回2597行。第一个查询是否没有返回整个24小时的时间段?此数据库中的日期字段为varchar(255),其中包含日期,小时,分钟和秒。什么是正确的方法呢?

2 个答案:

答案 0 :(得分:9)

;WITH [cteOrders] AS
(
    SELECT  CONVERT(DATE, [OrderDate]) AS [OrderDate],
            CONVERT(MONEY, [Total_Lines_Net]) AS [Total_Lines_Net]
    FROM [dbo].[Orders]
)
SELECT  [OrderDate],
        COUNT(*) AS [Rows],
        SUM([Total_Lines_Net]) AS [Total]
FROM [cteOrders]
WHERE DATEDIFF(DAY,[OrderDate],GETDATE()) <= 7
GROUP BY [OrderDate]
ORDER BY [OrderDate]

答案 1 :(得分:2)

  

此数据库中的日期字段是varchar(255),其中包含日期,小时,分钟和   秒。什么是正确的方法呢?

这里你的问题是。这太荒谬了;)

从一开始就将OrderDate字段设为DATE。

您的方法会触发表扫描和其他不良内容。