使用数据命名列

时间:2018-03-28 21:04:36

标签: sql sql-server

我有2个表,我想运行一个查询,我在其中一个表中使用一个值来更改dateadd使用的列。

table1
id      value    date1        date2          date3  
-------|-------|------------|------------|-----------|
1      | 10    | 04/03/2018 | 04/03/2017 |01/03/2016 |
2      | 1     | 04/03/2018 | 05/03/2015 |02/03/2018 |
3      | 2     | 04/03/2016 | 06/03/2016 |03/03/2018 |
4      | 1     | 04/03/2015 | 07/03/2018 |04/03/2017 |
5      | 2     | 04/03/2017 | 09/03/2018 |05/03/2019 |

table2
id      value   
-------|-------|
1      | date1 |
2      | date3 |
3      | date3 |
4      | date2 |
5      | date1 |

执行ID 1的常规方法类似于dateadd(month,10,date1)。如果没有我每次都写它,我不知道怎么做。

select *
from table1
join table2 on table1.id = table2.id
where DATEADD(month, table1.value, table1.[table2.value]) between '1/1/18' and '12/31/18'

2 个答案:

答案 0 :(得分:3)

第十二个回答是正确的。我只想看看他的理论是否有效,而且确实如此 - 这是一个有效的实施方案。

declare @table1 table (id int, value int, date1 date, date2 date, date3 date)
declare @table2 table (id int, colname varchar(5))

insert into @table1 values (1,10,'04/03/2018','04/03/2017','01/03/2016')
insert into @table1 values (2,1 ,'04/03/2018','05/03/2015','02/03/2018')
insert into @table1 values (3,2 ,'04/03/2016','06/03/2016','03/03/2018')
insert into @table1 values (4,1 ,'04/03/2015','07/03/2018','04/03/2017')
insert into @table1 values (5,2 ,'04/03/2017','09/03/2018','05/03/2019')

insert into @table2 values (1, 'date1')
insert into @table2 values (2, 'date3')
insert into @table2 values (3, 'date3')
insert into @table2 values (4, 'date2')
insert into @table2 values (5, 'date1')

select id, colname, newdate
from
(
    select sq.id, sq.colname, dateadd(month, sq.value, sq.dn) as newdate
    from @table1 t1
    unpivot
    (
        dn for colname in ([date1], [date2], [date3])
    )sq
    inner join @table2 t2 on sq.id = t2.id and sq.colname = t2.colname
)sq where newdate between '1/1/2018' and '12/31/2018'

输出:

id  colname newdate
2   date3   2018-03-03
3   date3   2018-05-03
4   date2   2018-08-03

答案 1 :(得分:2)

我已将此作为理论,你实际上是我可以尝试应用它的第一个提问者。我们的想法是取消您的数据,然后加入值列。

select id,column_name,value
from table1 t1
unpivot (
value
for column_name in (date1,date2,date3,date4,date5,date6,date7,date8,date9,date10)
) a
inner join table2 t2 on t1.id = t2.id and t2.value = a.column_name
where t2.value
between '1/1/18' and '12/31/18' 

我无法保证能够发挥作用并且很好奇它是如何为你做的。