根据时间范围拆分列

时间:2018-07-19 08:41:30

标签: sql tsql

我有两个具有这种结构的表:

表1:

Datefrom    Dateto       DIM_code
20160101    20161231     dim_1
20170101    20191231     dim_2 

表2:

Date        DIM_code
20160217    20
20170519    37

我需要一个这样的表:

表格-结果:

Date        dim_1    dim_2
20160217    20 
20170519             37

2 个答案:

答案 0 :(得分:0)

用例尚不清楚。您能否详细说明问题陈述?

根据您所解释的内容,这应该可以为您完成工作。

SELECT t2.Date,
       (CASE WHEN t2.DIM_code=20 THEN t2.DIM_code END) AS dim_1,
       (CASE WHEN t2.DIM_code=37 THEN t2.DIM_code END) AS dim_2
FROM Table2 t2 JOIN
     Table1 t1 
WHERE t2.Date between t1.Datefrom AND t1.Dateto;

但是我真的怀疑那是您要寻找的东西。

答案 1 :(得分:0)

我相信你想要

SELECT t2.Date,
       (CASE WHEN t1.DIM_code = 'dim_1' THEN t2.DIM_code END) AS dim_1,
       (CASE WHEN t1.DIM_code = 'dim_2' THEN t2.DIM_code END) AS dim_2
FROM Table2 t2 JOIN
     Table1 t1 
WHERE t2.Date >= t1.Datefrom AND
      t2.Date <= t1.Dateto;