选择SQL动态查询

时间:2018-05-31 11:13:18

标签: sql sql-server sql-server-2008

如何编写SQL查询动态值?

pos_id  start_date  Enddate
1       20140131    20141201
2      20150331     20151201

结果:

position_id startdate   Enddate Month   Year
1   20140131    20141201    1   2014
1   20140131    20141201    2   2014
1   20140131    20141201    3   2014
1   20140131    20141201    4   2014
1   20140131    20141201    5   2014
1   20140131    20141201    6   2014
1   20140131    20141201    7   2014
1   20140131    20141201    8   2014
1   20140131    20141201    9   2014
1   20140131    20141201    10  2014
1   20140131    20141201    11  2014
1   20140131    20141201    12  2014
2   20150331    20151201    3   2015
2   20150331    20151201    4   2015
2   20150331    20151201    5   2015
2   20150331    20151201    6   2015
2   20150331    20151201    7   2015
2   20150331    20151201    8   2015
2   20150331    20151201    9   2015
2   20150331    20151201    10  2015
2   20150331    20151201    11  2015
2   20150331    20151201    12  2015
select start_date,
cast(SUBSTRING(start_date,5,2)as int),end_date,cast(SUBSTRING(end_date,5,2)as int),
case when 
    cast(SUBSTRING(start_date,5,2)as int) < cast(SUBSTRING(end_date,5,2)as int)
then start_date end
as date_range
from [dbo].[SRC_TEST_DATE]

我可以比较值但是如何获得动态值。 提前谢谢。

2 个答案:

答案 0 :(得分:0)

递归子查询是一种简单的方法:

with cte as (
      select pos_id, startdate, enddate, startdate as yyyymm
      from t
      union all
      select pos_id, startdate, enddate, dateadd(month, 1, startdate)
      from t
      where yyyymm < enddate
     )
select pos_id, startdate, enddate, month(yyyymm), year(yyyymm)
from cte
order by pos_id, start_date, yyyymm;

答案 1 :(得分:0)

SELECT Position_ID, MONTH(DATEADD(MONTH, X.NUMBER, BEGDA)) PERIOD, 
YEAR(DATEADD(MONTH, X.NUMBER, BEGDA)) YEAR, BEGDA, ENdda 
from SRC_IN_TEST 
INNER JOIN 
MASTER.DBO.SPT_VALUES X 
ON 1 = 1 
WHERE X.TYPE = 'P' AND
X.NUMBER <= DATEDIFF(MONTH, CONVERT(DATE,LEFT(BEGDA,8)), 
CONVERT(DATE,LEFT(REPLACE(endda,9999,2024),8))