gpt4 book ai didi

sql-server - 在 sql server 中过去 7 天的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-01 08:17:06 26 4
gpt4 key购买 nike

我需要过去 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) , 其中包含日期、小时、分钟和秒。这样做的正确方法是什么?

最佳答案

;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]

关于sql-server - 在 sql server 中过去 7 天的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8433367/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com