如何动态选择表列?

时间:2013-09-13 17:14:35

标签: vba ms-access

我有一个数据表,其中有月份列(字段)。 如何编写一个动态选择当前月份列的查询?

我试过这样做:

SELECT MonthName(month(date())) FROM my_table

这不起作用,所以我尝试了几种不同的方法来返回查询的月份名称作为字段名称,但到目前为止没有任何效果。

有人能指出我的解决方案吗?

2 个答案:

答案 0 :(得分:1)

每个月都有一个包含列的数据源。您可以使用Switch()从名称与当前月份匹配的列中检索值。

SELECT
    Switch
        (
            Month(Date())= 1, [Jan],
            Month(Date())= 2, [Feb],
            Month(Date())= 3, [Mar],
            Month(Date())= 4, [Apr],
            Month(Date())= 5, [May],
            Month(Date())= 6, [Jun],
            Month(Date())= 7, [Jul],
            Month(Date())= 8, [Aug],
            Month(Date())= 9, [Sep],
            Month(Date())=10, [Oct],
            Month(Date())=11, [Nov],
            Month(Date())=12, [Dec]
        ) AS current_month_column
FROM my_table;

但是,我会尝试转换数据源,将列转换为行。

SELECT 'Jan' AS month_name, [Jan] As month_value FROM my_table
UNION ALL
SELECT 'Feb' AS month_name, [Feb] As month_value FROM my_table
UNION ALL
...

您可以将联合结果集存储在另一个表中并查询该联合查询或查询联合查询。

SELECT month_name, month_value
FROM YourTable
WHERE month_name = MonthName(Month(Date()), True);

答案 1 :(得分:0)

Dim db As Database
Dim strSQL As String

Set db = CurrentDb
strSQL = "SELECT " & left(MonthName(Month(Date)), 3) & " INTO new_table FROM my_table"
db.Execute strSQL