根据年份和月份选择数据

时间:2014-08-22 14:17:59

标签: sql sql-server

我有一个包含以下列的表:

ID | FromYear | FromMonth | ToYear | ToMonth | Details

1  |  2012    |    5      | 2012   |   7     |  xxx

1  |  2012    |    8      | 2013   |   2     |  yyy

1  |  2013    |    3      |  0     |   0     |  zzz

我有两个搜索参数 - 年份和月份 如果我搜索2012和6,第一行应该来,如果我搜索2013和1 第二排应该来...... To Year中的值为0,最后一行中的To Month表示最高值 日期记录,所以任何用2013年,3或更多搜索的记录都应该给第三行**强文**

2 个答案:

答案 0 :(得分:0)

假设您有两个变量@ SearchYear和@SearchMonth ...

select *
from YourTableName
where @SearchYear >= FromYear 
    and @SearchYear <= ToYear
    and @SearchMonth >= FromMonth
    and (@SearchMonth <= ToMonth or ToMonth = 0)

答案 1 :(得分:0)

听起来你需要这样的东西

SELECT
ID,FromYear, FromMonth,ToYear,ToMonth, Details
FROM <tablename>
WHERE --FromYear & FromMonth before or the same as parameters
(
    (FromYear = @year AND FromMonth <= @month)  -- Same year, Earlier Month than parameters
    OR 
    FromYear < @year                            -- Earlier Year than parameter
)
AND --ToYear & ToMonth after or the same as parameters (or both zero)
(
    (ToYear= @year AND ToMonth >= @month) -- Same Year, Later Month than parameters
    OR
    ToYear > @year                         -- Later Year than parameter
    OR
    (ToYear= 0 AND ToMonth = 0)           -- ToYear,ToMonth are zero
)