简体   繁体   English

SQL查询以查找最后日期

[英]SQL query to find last date

We enter our production data in the database next day of production, I am using the following query to get the yesterday data. 我们将生产的第二天在数据库中输入生产数据,我正在使用以下查询来获取昨天的数据。

Query works fine until after weekend, it shows nothing on Monday because there is no production on weekend. 查询工作正常,直到周末之后,由于星期一没有生产,星期一不显示任何内容。

Is there anyway I can change the query to show me the last day of production. 无论如何,我可以更改查询以显示生产的最后一天。

SELECT Date, ProductCode
FROM Production
WHERE (ProductCode In ('35032','40112-I','41212-I','50112','824-5'))                   
AND (Date=Dateadd(dd,-1,Convert(char(8),Current_timestamp,112)))

A simple solution with a CASE statement to check to see if it's a Monday, and if so, subtract 3 days rather than 1. 一个简单的解决方案,使用CASE语句检查是否为星期一,如果是,则减去3天而不是1天。

SELECT  Date, ProductCode
FROM    Production
WHERE   (ProductCode In ('35032','40112-I','41212-I','50112','824-5'))                   
AND     (Date=Dateadd(Day, Case When DatePart(WeekDay, Current_Timestamp) = 2 Then -3 Else -1 End, Convert(Date, Current_Timestamp)))

Another (more precise) solution would be to pull the most recent Date in the table that isn't today's Date : 另一个(更精确的)解决方案是将表中的最新Date拉出,而不是今天的Date

SELECT  Date, ProductCode
FROM    Production
WHERE   (ProductCode In ('35032','40112-I','41212-I','50112','824-5'))                   
AND     (Date= (Select Max(Date) From Production Where Date <> Convert(Date, Current_Timestamp)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM