如何使用sql server获取最后一个工作日的记录

时间:2015-05-27 06:17:38

标签: sql sql-server

我需要查询SQL数据库,以便在上次工作日期获取所有购买的产品。例如,在Monday上,我需要获取Saturday的记录。另外假设由于某种原因Tuesday是我的假,我需要获取Monday的记录。 我尝试了我的查询:

select ProductName , count(ProductName) as [No Of Products],SUM(Total) as [TotalCost] 
from dbo.TransactionDetails 
where CurrentTime >=dateadd(day,datediff(day,1,GETDATE()),0) 
    AND CurrentTime <dateadd(day,datediff(day,0,GETDATE()),0) 
    and  Transaction='BUY' 
group by ProductName

但在这里,我只获得了上次约会的详细信息。

我还试着查看我上次关闭的班次:

select ProductName , count(ProductName) as [No Of Products],SUM(Total) as [TotalCost] 
from dbo.TransactionDetails 
where CurrentTime = (select MAX(CurrentDateTime) from CloseShifts) and  Transaction='BUY' 
group by ProductName

但问题是在这里我没有得到任何结果,因为下面的查询返回DateTime,并且在那个特定的时间我没有任何交易。

select MAX(CurrentDateTime) 
from CloseShifts

3 个答案:

答案 0 :(得分:3)

select ProductName , count(ProductName), SUM(Total), MAX(CurrentDateTime) from "dbo.TransactionDetails"  inner join在两个表之间使用CloseShifts条件(因为你没有提供表格)“

答案 1 :(得分:1)

试试这个

 select ProductName , count(ProductName) as [No Of Products],SUM(Total) as [TotalCost] 
    from dbo.TransactionDetails 
    where CurrentTime >=dateadd(day,datediff(day,1,(select MAX(CurrentDateTime) 
    from CloseShifts)),0) 
    AND CurrentTime <dateadd(day,datediff(day,0,(select MAX(CurrentDateTime) 
    from CloseShifts)),0) 
    and  Transaction='BUY' 
    group by ProductName

答案 2 :(得分:1)

如果我正确读取这个,你需要删除DateTime列的“Time”部分,那么如何将DateTimes作为Dates转换,例如:

... where Cast(CurrentTime as DATE) = (select MAX(Cast(CurrentDateTime as DATE)) ...