sql - How to get name of column for use in SELECT clause -
i have table in access db has columns each of 12 months of year. columns have names of "1" "12". say, names of columns number of month represents. columns contain numbers data, , need sum columns months remaining in year. example, right we're in september, i'd need select
clause sum values in columns (months) 9 through 12. must able dynamically sum relevant months, next month (oct) sep excluded , 10 through 12 summed.
how can reference name of column in select
clause able perform test on it. need following:
iif(table1.[1].columnname >= month(now), table1.[1], 0) + iif(table1.[2].columnname >= month(now), table1.[2], 0) ... + iif(table1.[12].columnname >= month(now), table1.[12], 0)
this 1 approach, but, in passing, if there's better way this, please let me know well.
i've seen other posts on discuss returning column names table. not need here. need return column name , perform tests on within select
clause. thanks.
edit understand structure (having data across 12 different columns) not greatest. not new db i'm setting up. old db i've inherited, can't make changes structure.
not sure understood question, seem major issue fact store values in different columns instead of .
one solution use union
in subquery make columns available outer select , use filter, sum , group by.
if have table looking like:
id (number, primary key), 1..12 (number, month values)
then query should work (this month 1-5 only):
select id, sum(monthvalue) sumfuturemonths ( select 1 monthno, id, yourtable.[1] monthvalue yourtable union select 2 monthno, id, yourtable.[2] monthvalue yourtable union select 3 monthno, id, yourtable.[3] monthvalue yourtable union select 4 monthno, id, yourtable.[4] monthvalue yourtable union select 5 monthno, id, yourtable.[5] monthvalue yourtable ) monthno > month(now()) group id
whether perform can't - depends on data, retrieving data in table union can costly operation. anyway, please try out see if works.
Comments
Post a Comment