简体   繁体   中英

How to pick the column dynamically based on month in SQL

Need your help bring such a way the below format.. i am pretty must confused to bring the format dynamically every month,Because every month the column name has to be swap between MO or Adj_M0

If you see my example 表结构和输出格式

When you see the above format which i need for every month. Ex: refer Ouput - Jan (Column Name) will swap compare to Ouput - Feb

Similar like it will swap the column on every month , so can you please guide me how to bring my output format.

Hope your understand,pls guide me or give me some sample code

So lets build the SQL dynamically each time it is run. Start with and then tune it to get your desired results --

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

When the month is 5, the resulting SQL is --

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM