如何在SQL中基于月份动态选择列

时间:2014-01-25 06:41:10

标签: sql sql-server-2008

需要你的帮助带来以下格式的这种方式..我非常必须混淆每月动态带来格式,因为每个月的列名必须在MO或Adj_M0之间交换

如果您看到我的示例Table structure and ouput format

当你看到我每个月需要的上述格式时。 例如:参考输出 - Jan(列名称)将交换比较输出 - 2月

类似于它会在每个月交换列,所以请指导我如何使用我的输出格式。

希望你理解,请指导我或给我一些示例代码

1 个答案:

答案 0 :(得分:0)

因此,每次运行时都要动态构建SQL。开始,然后调整它以获得所需的结果 -

Function fnMakeTheSQL(nMO As Long) As String

    ' define the output SQL string, and initialize it to blanks
    Dim sSQL As String
    sSQL = ""

    ' concat the first part of the SQL
    sSQL = sSQL & " SELECT  "
    sSQL = sSQL & vbCrLf & "   Name, "
    sSQL = sSQL & vbCrLf & "   M0, "

    ' now the interesting part, the LOOPing to build Prior & This month-s columns
    Dim iMO As Long
    For iMO = 1 To nMO
        sSQL = sSQL & vbCrLf & "   M" & iMO & ", "
    Next iMO

    ' and more interesting part, the LOOPing to build Future ADJ columns
    'Dim iMO As Long
    For iMO = nMO + 1 To 12
        sSQL = sSQL & vbCrLf & "   ADJ_M" & iMO & ", "
    Next iMO

    ' strip off the trailing comma
    sSQL = Left(sSQL, InStrRev(sSQL, ",") - 1)

    ' concat the last part of the SQL
    sSQL = sSQL & vbCrLf & "  From  yourTable "
    sSQL = sSQL & vbCrLf & "  Order By Name "

    ' give it back to the caller
    fnMakeTheSQL = sSQL

End Function

当月份为5时,生成的SQL为 -

SELECT  
Name, 
M0, 
M1, 
M2, 
M3, 
M4, 
M5, 
ADJ_M6, 
ADJ_M7, 
ADJ_M8, 
ADJ_M9, 
ADJ_M10, 
ADJ_M11, 
ADJ_M12
From  yourTable 
Order By Name