我创建了一个“每日销售查询”,以捕获从前一个工作日(星期一至星期五,上午8点)输入的所有销售总额。
问题是,如果今天是星期一,我如何才能捕获星期五的记录。 这样我就可以排除周末。
因为是星期一,所以总销售额显示为0,这实际上是有道理的,因为星期日不是工作日。请协助。
查看我当前的代码:
SELECT
CONVERT(VARCHAR, DATEADD(dd, - 1, GETDATE()), 103) AS Date,
'Sales Orders' AS Type,
COUNT(o.SalesOrderID) AS Orders,
SUM(d.QtyOrdered) AS Chairs,
ISNULL(ROUND(SUM(d.ExtendedPrice), 2), 0) AS [Total Ex GST]
FROM
dbo.SalesOrder o
LEFT OUTER JOIN
dbo.SalesOrderDetails d ON o.SalesOrderID = d.SalesOrderID
WHERE
(o.EntryDate >= CONVERT(CHAR(8), DATEADD(dd, - 1, GETDATE()), 112))
AND (o.EntryDate < CONVERT(CHAR(8), GETDATE(), 112))
AND (o.CustomerID <> 187);
答案 0 :(得分:1)
您可以使用datediff(dd,0,getdate()) % 7 = 0
来确定当前日期是否为星期一,而不考虑其他任何服务器设置(这是因为SQL Server中的零日期为1900-01-01,恰好是星期一)。
declare @start date;
declare @finish date;
set @start = dateadd(dd, case when datediff(dd,0,getdate()) % 7 = 0 then -3 else -1 end, getdate());
set @finish = dateadd(dd,1,@start);
select
@start, datename(weekday,@start)
, @finish, datename(weekday,@finish)
, datename(weekday,getdate())
;
因此在您的查询中,我将使用:
declare @start date;
declare @finish date;
set @start = dateadd(dd, case when datediff(dd,0,getdate()) % 7 = 0 then -3 else -1 end, getdate());
set @finish = dateadd(dd,1,@start);
SELECT
CONVERT(VARCHAR, @start, 103) AS Date,
'Sales Orders' AS Type,
COUNT(o.SalesOrderID) AS Orders,
SUM(d.QtyOrdered) AS Chairs,
ISNULL(ROUND(SUM(d.ExtendedPrice), 2), 0) AS [Total Ex GST]
FROM
dbo.SalesOrder o
LEFT OUTER JOIN
dbo.SalesOrderDetails d ON o.SalesOrderID = d.SalesOrderID
WHERE
o.EntryDate >= @start
AND o.EntryDate < @finish
AND o.CustomerID <> 187
;
答案 1 :(得分:0)
如果您使用案例声明来确定过去需要几天,例如
dateadd(dd, case when datepart(weekday,getdate()) = 1 then -3 else -1 end, getdate()) -- StartDate
dateadd(dd, case when datepart(weekday,getdate()) = 1 then -2 else 0 end, getdate()) -- EndDate
所以您的代码看起来像
SELECT
CONVERT(VARCHAR, dateadd(dd, case when datepart(weekday,getdate()) = 1 then -3 else -1 end, getdate()), 103) AS Date,
'Sales Orders' AS Type,
COUNT(o.SalesOrderID) AS Orders,
SUM(d.QtyOrdered) AS Chairs,
ISNULL(ROUND(SUM(d.ExtendedPrice), 2), 0) AS [Total Ex GST]
FROM
dbo.SalesOrder o
LEFT OUTER JOIN
dbo.SalesOrderDetails d ON o.SalesOrderID = d.SalesOrderID
WHERE
(o.EntryDate >= CONVERT(CHAR(8), dateadd(dd, case when datepart(weekday,getdate()) = 1 then -3 else -1 end, getdate()), 112))
AND (o.EntryDate < CONVERT(CHAR(8), dateadd(dd, case when datepart(weekday,getdate()) = 1 then -2 else 0 end, getdate()), 112))
AND (o.CustomerID <> 187);
PS:请确保服务器上的工作日1
是星期一。