Home > Blockchain >  Need help to build my SQL Query executed in VBA
Need help to build my SQL Query executed in VBA

Time:11-10

I have made the following group by query :

SQL = " SELECT DISTINCTROW [A], [B], [C],[D], Sum([E]) AS [Sum E]" & _
      " FROM [SheetName$RangeAddress]" & _
      " GROUP BY [A], [B], [C],[D];"

But this does return a too large amount of data where I wish to have only the TOP 5 so I've try to do the following :

SQL = " SELECT TOP 5 FROM (SELECT DISTINCTROW [A], [B], [C],[D], Sum([E]) AS [Sum E]" & _
      " FROM [SheetName$RangeAddress]" & _
      " GROUP BY [A], [B], [C],[D]) ORDER BY [Sum E] DESC;"

But this does not work and throw the following error :

The SELCT Statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect

What am I missing ?

CodePudding user response:

Try this:

SQL = " SELECT TOP 5 * FROM" & _
      "     (SELECT DISTINCTROW [A], [B], [C], [D], Sum([E]) AS [Sum E]" & _
      "     FROM [SheetName$RangeAddress]" & _
      "     GROUP BY [A], [B], [C], [D]) AS T"
      " ORDER BY T.[Sum E] DESC;"
  • Related