我很难找到一个查询,该查询以与存储effectiveDates的表相关的表中的记录为目标。
假设我有这三个表:
tblProjects
-----------
id
tblTickets
----------
id
projectID
ticketNumber
ticketDate
tblRates
--------
id
projectID
effectiveDate
payRate
我要做的是创建一个查询,根据ticketDate测试Rates表的effectiveDate,并找到最新的effectiveDate,它是< = ticketDate。查找最新信息很重要,因为可能有几个适用于项目的不同速率值。
所以tblTickets可能有:
id projectId ticketDate ticketNumber
-----------------------------------------------------------
1 1 2016/08/11 990
2 1 2016/09/12 991
3 1 2016/10/22 992
4 1 2016/10/23 993
5 2 2016/08/15 750
6 2 2016/09/08 751
和tblRates可能有:
id projectId effectiveDate Rate
-----------------------------------------------------------
1 1 2016/08/01 $50
2 1 2016/10/01 $75
3 2 2016/06/01 $65
如果我要查询projectId = 1的所有故障单,我希望看到这样的内容:
projectId ticketNumber TicketDate Rate
------------------------------------------------------------------------
1 990 2016/08/11 $50
1 991 2016/09/12 $50
1 992 2016/10/12 $75
1 993 2016/10/23 $75
我甚至不确定从哪里开始。我可以查询effectiveDate的MAX但是只会返回上面示例中的10/12和10/23记录。我也可以简单地查询所有< = TicketDate,但是因为08/01和10/01都属于该标准,所以会返回重复项。
非常感谢正确方向的推动!
编辑: 这是我当前的查询。它会返回每个费率的所有记录的副本。
SELECT
vRates.projectId
, tblTickets.TicketNumber
, tblTickets.TicketDate
, vRates.Rate
, vRates.effectiveDate
FROM (
( SELECT
vTempRates.effectiveFrom
, vTempRates.projectId
, vRates.Rate
FROM tblRates AS vTempRates
INNER JOIN
( SELECT
projectId
, MAX(effectiveFrom) AS effectiveDate
, Rate
FROM tblRates
GROUP BY projectId, Rate
) AS vRates
ON vTempRates.projectId = vRates.projectId
AND vTempRates.effectiveFrom = vRates.effectiveDate
) AS vRates
INNER JOIN tblProjects
ON vRates.projectId = tblProjects.id)
INNER JOIN tblTickets
ON tblProjects.id = tblTickets.projectId
WHERE (((tblProjects.id)=1));
答案 0 :(得分:1)
select t.*
,(select top 1 r.Rate from tblRates r where r.projectid = t.projectid and r.effectiveDate <= t.ticketDate order by r.effectiveDate desc) as Rate
from tblTickets t
where t.projectid = 1
;
答案 1 :(得分:0)
所以我经历了你的问题,我想如果我是正确的,那么用以下方法做这件事真的很容易:
Select effectivedate from Rates R join Projects p on R.projectId= p.id join
Tickets T on T.projectId = p.id where
effectivedate<= t.ticketdate
order by effectivedate desc
limit 1;
此查询基本上会选择相应的生效日期。现在order by子句的输出将按照您最近的格式到最新的格式进行排序,然后限制1将返回最新日期。
如果您想拥有最近3个最新日期,您可以随时增加限制关键字中的数字,如下所示:
limit 3
这将返回最近3个最新日期。
我希望这很有用。
答案 2 :(得分:0)
SELECT tic.projectId projectId,tic.ticketNumber ticketNumber , tic.ticketDate ticketDate ,(SELECT top 1 Rate FROM tblRates WHERE ticketDate >= effectiveDate AND tblRates.projectId = Tic.projectId ORDER BY effectiveDate DESC) Rate
FROM tblTickets Tic WHERE Tic.projectId = 1