where子句基于另一个表中的select语句

时间:2015-07-09 10:29:16

标签: sql-server

我正在撰写的查询需要帮助。我基本上想从一个表中选择所有GRNID,但它们必须在另一个表中的日期之间。

所以我想要在ABSPeriodEndDate表中找到的两个日期之间的所有GRN。要找出between子句的开始日期,我需要找到MAX Period然后减去1和最大年份。

要查找之间条款的结束日期,我想要找到最长期和年份。但我希望DateStamp列返回between子句的结果。

关于如何解决这个问题的任何想法我似乎无法按照我的意愿运作。

我的查询如下:

SELECT tblGRNItem.GRNID 
FROM tblGRNItem
INNER JOIN ABSPeriodEndDates ON tblGRNItem.DateCreated = ABSPeriodEndDates.DateStamp
WHERE tblGRNItem.DateCreated BETWEEN
SELECT ABSPeriodEndDates.DateStamp FROM ABSPeriodEndDates WHERE ABSPeriodEndDates.DateStamp = (SELECT MAX(ABSPeriodEndDates.Period)-1 FROM ABSPeriodEndDates) 
AND ABSPeriodEndDates.Year = (SELECT MAX(ABSPeriodEndDates.Year))) 
AND 
SELECT ABSPeriodEndDates.DateStamp FROM ABSPeriodEndDates WHERE ABSPeriodEndDates.DateStamp = (SELECT MAX(ABSPeriodEndDates.Period) FROM ABSPeriodEndDates) 
AND ABSPeriodEndDates.Year = (SELECT MAX(ABSPeriodEndDates.Year)))

注意:ABSPeriodEndDates中的DataStamp是datetime2数据类型,tblGRNItem中的DateCreated是日期时间数据类型。

示例数据:

tblGRNItem                          ABSPeriodEndDates

GRNID || DateCreated                Year  || Period  || DateStamp
1     || 01/01/2015                 2015  ||   1     || 01/01/2015 00:00:01
2     || 05/01/2015                 2015  ||   1     || 01/01/2015 00:00:01
3     || 06/02/2015                 2015  ||   2     || 01/02/2015 00:00:01
4     || 09/02/2015                 2015  ||   2     || 01/02/2015 00:00:01
5     || 19/02/2015                 2015  ||   2     || 01/02/2015 00:00:01
6     || 16/03/2015                 2015  ||   3     || 01/03/2015 00:00:01

因此,因为最大期间减1是2且最大期间是3我想从tblGRNItem获取所有GRNID来自日期戳01/02/2015 00:00:01和01/03/2015 00:00:01之间请记住,数据类型是在ABSPeriodEndDates中的tblGRNitem和datetime2中的日期时间,因此结果应为:

3     || 06/02/2015      
4     || 09/02/2015               
5     || 19/02/2015  

提前致谢

2 个答案:

答案 0 :(得分:2)

感谢Shnugo工作但我也解决了它:

declare @StartDate datetime;
set @StartDate= (SELECT Max(DateStamp)
from ABSPeriodEndDates as P
where P.Period = (SELECT Max(Period) -1 from ABSPeriodEndDates)
and P.Year = (SELECT Max(Year) from ABSPeriodEndDates));

declare @EndDate datetime;
set @EndDate= (SELECT top (1) DateStamp
from ABSPeriodEndDates 
order by Period desc, DateStamp desc);

SELECT GRNID 
from tblGRNItem
where DateCreated between @StartDate and @EndDate;

答案 1 :(得分:1)

在不知道您的数据的情况下,无法给您答案。 因为看起来ABSPeriodEndDates和tblGrnItem之间没有联系。你只想找到最新的periode范围,是吗?

你可以做这样的事情

 WITH MaxDat AS
(
    SELECT MAX(DateStamp) AS MaxDatFound
    FROM ABSPeriodEndDates
)
,MinDat AS
(
    SELECT TOP 1 DateStamp AS MinDatFound
    FROM ABSPeriodEndDates
    WHERE DateStamp<(SELECT MaxDatFound FROM MaxDat)
    ORDER BY DateStamp DESC 
)
SELECT * 
FROM  tblGRNItem
WHERE DateCreated BETWEEN (SELECT MinDatFound FROM MinDat) AND (SELECT MaxDatFound FROM MaxDat)