需要你的帮助带来这样一种方式下面的格式..我很必须混淆每个月动态地带来格式,因为每个月的列名必须交换MO或Adj_M0如何在SQL中根据月份动态地选择列
如果你看到我的例子
当你看到上面的格式,我需要每月。 例如:参考输出 - 1月(列名)将交换与输出比较 - Feb
类似它会交换每月的列,所以你可以请指导我如何带来我的输出格式。
希望你明白,请指导我或者给我一些示例代码
需要你的帮助带来这样一种方式下面的格式..我很必须混淆每个月动态地带来格式,因为每个月的列名必须交换MO或Adj_M0如何在SQL中根据月份动态地选择列
如果你看到我的例子
当你看到上面的格式,我需要每月。 例如:参考输出 - 1月(列名)将交换与输出比较 - Feb
类似它会交换每月的列,所以你可以请指导我如何带来我的输出格式。
希望你明白,请指导我或者给我一些示例代码
所以,让我们建立动态的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
在表中有哪些列?表结构不显示名为Adj_M5,Adj_M6,Adj_M7,Adj_M8,Adj_M9的列,这些列出现在稍后的月份。表中有多少个月份的专栏?您是否尝试过每个月动态构建SQL?让我们看看... tkx – donPablo
嗨DonPablo,对不起,我错过了表格结构中的柱面名称..但是我一直到Adj_M12在我的表 – Venki