![](/img/trans.png)
[英]Selecting rows that are within a date range based on a date from another table. (MYSQL)
[英]Using join to match table rows based on a date falling within a range
我試圖將世界銀行國家收入水平映射到數據集。 收入水平每年都在變化,我需要使用交易的國家和日期將適當的收入水平映射到交易。
下表說明了布局和問題:
Example - Table 1 Table 2
----------------- ----------------------------------------
|ISOCountryCode3, PODate | |CountryAlpha3, StartDate, EndDate, IncomeClass|
|CIV, '2009-11-01' | | CIV, 1989-10-02, 1989-09-12, lower |
|ALB, '2007-01-04' | | CIV, 2009-01-01, 2010-01-01, lower |
| CIV, 2010-01-02, 2011-01-01, middle |
系統應返回:
|CIV, '2009-11-01', lower|
|...
這是我到目前為止嘗試過的SQL
SELECT mergestandard.*,incomeclassifications.IncomeClass
FROM `mergestandard`
LEFT OUTER JOIN incomeclassifications
ON mergestandard.ISOCountryCode3 = incomeclassifications.CountryAlpha3
AND mergestandard.PODate<=incomeclassifications.EndDate
AND mergestandard.PODate>=incomeclassifications.StartDate
不幸的是,系統在incomeclass字段中保持返回null。 任何幫助將非常感激!
我通常不使用mySql,但我會試試這個:
SELECT mergestandard.*,incomeclassifications.IncomeClass
FROM `mergestandard`
LEFT OUTER JOIN incomeclassifications
ON mergestandard.ISOCountryCode3 = incomeclassifications.CountryAlpha3
WHERE
mergestandard.PODate<=incomeclassifications.EndDate
AND mergestandard.PODate>=incomeclassifications.StartDate
第一部分會給你
|CIV, '2009-11-01', lower|
|CIV, '2009-11-01', lower|
|CIV, '2009-11-01', middle|
|...
其中實際上還包括日期
|CIV, '2009-11-01', lower| 1989-10-02, 1989-09-12
|CIV, '2009-11-01', lower| 2009-01-01, 2010-01-01
|CIV, '2009-11-01', middle| 2010-01-02, 2011-01-01
|...
然后使用where子句過濾所需的內容。
|CIV, '2009-11-01', lower| 2009-01-01, 2010-01-01
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.