I want to run a string dynamically.
I'm trying to run a VBA loop to build a SQL Union for each record after the first. There could be anywhere from 1 record to 100. I want this to be dynamic so I don't have to limit the number of entries.
Example:
If I have 5 records it creates the SQL query with 4 unions. All the same data etc.
I'm trying to do is this:
When someone opens a form they will enter a list of pack numbers, from that they will select the range of offers under each pack number (All Offers, Promo, or Buyer).
The code then builds a union query for each pack number based on the the offer range they selected.
The output is all the data on those Offers under that pack number.
My full code: (I thought it necessary to get the full picture)
Private Sub ReviewButton_Click()
Dim Owner As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim qdfPassThrough As QueryDef
Dim strSeasonSQL As String
Dim strSeason As String
Dim strType As String
Owner = GetNamespace("MAPI").Session.CurrentUser.AddressEntry
If Me.NewRecord = True Then
Me!Owner.Value = Owner
End If
Set db = CurrentDb
Set rs = CurrentDb.OpenRecordset("RetailEntry")
'Set rs = CurrentDb.OpenRecordset("SELECT * FROM RetailEntry")
strSeason = [Forms]![Retail_Navigation]![NavigationSubform].[Form]![cboSeason]
strType = rs.Fields("Offer").Value '[Forms]![ReviewButton]![RetailEntry].[Form]![Offer].Value
On Error GoTo 1
1:
'Build Initial Query based on first record and make sure there are records
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'All Offers
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If rs.Fields("Offer") = "All Offers" Then
StrSQL = "Set NoCount ON DROP TABLE #catcov; " _
& "SELECT DISTINCT mailyear, offer, description, firstreleasemailed, season_id, offer_type, " _
& "case when description like '%Promo%' then 'Promo' " _
& "Else 'Buyer' end As addtype " _
& "INTO #catcov " _
strSELECT = "FROM supplychain_misc.dbo.catcov; " _
& "SELECT DISTINCT " _
& "a.PackNum " _
& ",a.Description " _
& ",a.CatID " _
& ",DATEPART(QUARTER, FirstReleaseMailed) as Quarter " _
& ",a.RetOne " _
& ",a.Ret2 " _
& ",a.ORIGINALRETAIL " _
& ",a.DiscountReasonCode " _
& ",b.Season_id " _
& ",a.year " _
& ",addtype "
strFROM = "FROM PIC704Current a JOIN #CatCov b ON (a.CatID = b.Offer) and (a.Year = b.MailYear) " _
strWHERE = "WHERE b.Offer_Type In('catalog', 'insert', 'kicker', 'statement insert', 'bangtail', 'onsert', 'outside ad') " _
& " and b.Season_id = '" & strSeason & "' " _
& " and (Case when b.FirstReleaseMailed >= cast(dateadd(day, +21, getdate()) as date) then 1 else 0 end) = 1 "
StrSQL = StrSQL & vbCrLf & strSELECT & vbCrLf & strFROM & vbCrLf & strWHERE
'Promo/Core
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
ElseIf rs.Fields("Offer") = "Promo" Or rs.Fields("Offer") = "Buyer" Then
StrSQL = "Set NoCount ON DROP TABLE #catcov; " _
& "SELECT DISTINCT mailyear, offer, description, firstreleasemailed, season_id, offer_type, " _
& "case when description like '%Promo%' then 'Promo' " _
& "Else 'Buyer' end As addtype " _
& "INTO #catcov " _
strSELECT = "FROM supplychain_misc.dbo.catcov; " _
& "SELECT DISTINCT " _
& "a.PackNum " _
& ",a.Description " _
& ",a.CatID " _
& ",DATEPART(QUARTER, FirstReleaseMailed) as Quarter " _
& ",a.RetOne " _
& ",a.Ret2 " _
& ",a.ORIGINALRETAIL " _
& ",a.DiscountReasonCode " _
& ",b.Season_id " _
& ",a.year " _
& ",addtype "
strFROM = "FROM PIC704Current a JOIN #CatCov b ON (a.CatID = b.Offer) and (a.Year = b.MailYear) " _
strWHERE = "WHERE b.Offer_Type In('catalog', 'insert', 'kicker', 'statement insert', 'bangtail', 'onsert', 'outside ad') " _
& " and b.Season_id = '" & strSeason & "' and b.addtype = '" & strType & "' " _
& " and (Case when b.FirstReleaseMailed >= cast(dateadd(day, +21, getdate()) as date) then 1 else 0 end) = 1 "
StrSQL = StrSQL & vbCrLf & strSELECT & vbCrLf & strFROM & vbCrLf & strWHERE
End If
'Build/Loop Unions for each record after the first
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
rs.MoveNext
strType = rs.Fields("Offer").Value
Do Until rs.EOF = True
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'All Offers
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If rs.Fields("Offer") = "All Offers" Then
StrUnion = "UNION SELECT DISTINCT " _
& "a.PackNum " _
& ",a.Description " _
& ",a.CatID " _
& ",DATEPART(QUARTER, FirstReleaseMailed) as Quarter " _
& ",a.RetOne " _
& ",a.Ret2 " _
& ",a.ORIGINALRETAIL " _
& ",a.DiscountReasonCode " _
& ",b.Season_id " _
& ",a.year " _
& ",addtype "
strFROMnxt = "FROM PIC704Current a JOIN #CatCov b ON (a.CatID = b.Offer) and (a.Year = b.MailYear) " _
strWHEREnxt = "WHERE b.Offer_Type In('catalog', 'insert', 'kicker', 'statement insert', 'bangtail', 'onsert', 'outside ad') " _
& " and b.Season_id = '" & strSeason & "' " _
& " and (Case when b.FirstReleaseMailed >= cast(dateadd(day, +21, getdate()) as date) then 1 else 0 end) = 1 "
StrSQL2 = StrUnion & vbCrLf & strFROMnxt & vbCrLf & strWHEREnxt
'Promo/Buyer
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
ElseIf rs.Fields("Offer") = "Promo" Or rs.Fields("Offer") = "Buyer" Then
StrUnion = "UNION SELECT DISTINCT " _
& "a.PackNum " _
& ",a.Description " _
& ",a.CatID " _
& ",DATEPART(QUARTER, FirstReleaseMailed) as Quarter " _
& ",a.RetOne " _
& ",a.Ret2 " _
& ",a.ORIGINALRETAIL " _
& ",a.DiscountReasonCode " _
& ",b.Season_id " _
& ",a.year " _
& ",addtype "
strFROMnxt = "FROM PIC704Current a JOIN #CatCov b ON (a.CatID = b.Offer) and (a.Year = b.MailYear) " _
strWHEREnxt = "WHERE b.Offer_Type In('catalog', 'insert', 'kicker', 'statement insert', 'bangtail', 'onsert', 'outside ad') " _
& " and b.Season_id = '" & strSeason & "' and b.addtype = '" & strType & "' " _
& " and (Case when b.FirstReleaseMailed >= cast(dateadd(day, +21, getdate()) as date) then 1 else 0 end) = 1 "
StrSQL2 = StrUnion & vbCrLf & strFROMnxt & vbCrLf & strWHEREnxt
End If
'Move to next Record and loop till EOF
rs.MoveNext
Loop
'If there are no Records then error
Else
MsgBox "There are no Pack Numbers Entered."
End If
'END QUERY
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Build Retail Bump File Pass Through Query
db.QueryDefs.Delete "qryMaster"
Set qdfPassThrough = db.CreateQueryDef("qryMaster")
qdfPassThrough.Connect = "ODBC;DSN=SupplyChainMisc;Description=SupplyChainMisc;Trusted_Connection=Yes;DATABASE=SupplyChain_Misc;"
qdfPassThrough.ReturnsRecords = True
qdfPassThrough.sql = StrSQL & vbCrLf & StrSQL2
rs.Close
Set rs = Nothing
DoCmd.OpenForm "SubCanButton"
DoCmd.OpenQuery "MasterQuery"
DoCmd.Close acForm, "ReviewButton"
End Sub
First, you do a "union distinct" when you don't include ALL:
UNION ALL
SELECT DISTINCT ...
Thus, as your selected records seem the same, only one will returned.
Second, including ALL or not, your concept doesn't make much sense. Why union a lot of identical records? Even if they hold different IDs only, they seem to be pulled from the same table, which you could with a single query.
Third, casting a date value to a date value does nothing good, so:
cast(dateadd(day, +21, getdate()) as date)
can be reduced to:
dateadd(day, +21, getdate())
Related
Public Sub UpdateTermFeedbackAddlReqt(ByVal runid As Integer, ByVal BHTerm As String, ByVal username As String, ByVal currtime As Double)
Dim db As DAO.Database
Dim rs As DAO.Recordset
DoCmd.SetWarnings False
Set db = CurrentDb
sql = "SELECT tbl_SCG_ExpectedTraffic.BHTerm, Sum(tbl_SCG_ExpectedTraffic.CurrSent2) AS SumOfCurrSent2, iif(Sum([CurrSent2]) = 0, 0, Sum([Accepted])/Sum([CurrSent2])) AS [Term Accept Rate], Sum(tbl_SCG_ExpectedTraffic.Accepted) AS SumOfAccepted, Sum(tbl_SCG_ExpectedTraffic.Rejected) AS SumOfRejected, Sum(tbl_SCG_ExpectedTraffic.Modified) AS SumOfModified, Sum(tbl_SCG_ExpectedTraffic.CurrCalledin) AS SumOfCalledin, Sum([ExpTotal])-Sum([CurrSent2]) AS [Need to Send]" & _
" FROM tbl_SCG_ExpectedTraffic" & _
" GROUP BY Date(), tbl_SCG_ExpectedTraffic.BHTerm, tbl_SCG_ExpectedTraffic.OptRunID" & _
" HAVING (((tbl_SCG_ExpectedTraffic.OptRunID)=" & runid & ") And BHTerm= """ & BHTerm & """);"
Set rs = db.OpenRecordset(sql, dbOpenDynaset, dbSeeChanges)
DoCmd.RunSQL ("Update tbl_SCG_TerminalFeedback set [CurrentSend2] = " & rs![SumOfCurrSent2] & ", [Term Accept Rate] =" & rs![Term Accept Rate] & ", Accepted= " & rs![SumOfAccepted] & ", Rejected = " & rs![SumOfRejected] & ", Modified =" & rs![SumOfModified] & ", Calledin = " & rs![SumOfCalledin] & ", AddlReqst =" & rs![Need To Send] & _
",[Last Update User] =""" & username & """, [Last Update Time]= " & currtime & " , HrDiff = iif( isnull(DLookup(""SubmissionDT"", ""tbl_SCG_OptRunSummary"", ""OptRunID = " & runid & """)), 0, Round((" & currtime & " - DLookup(""SubmissionDT"", ""tbl_SCG_OptRunSummary"", ""OptRunID =" & runid & """)) * 24, 1))" & _
" where OptRunID = " & runid & " And Term = """ & BHTerm & """")
DoCmd.SetWarnings True
rs.Close
db.Close
End Sub
So, I am trying to figure out where the TOTAL_CHG is coming from. Below is a snippet of where it is first used (not defined at all before).
...
sStrBalance = " (TOTAL_CHG - (ISNULL((SELECT SUM(isnull(t.amount, 0)) FROM transactions t " & _
" WHERE cp.contpolid = t.contpolid AND t.tran_date <= '" & GRepdate & "'), 0) + " & _
" ISNULL((SELECT SUM(isnull(dirpayamt, 0)) FROM bkrtrans bkr " & _
" WHERE cp.contpolid = bkr.contpolid), 0))) "
...
And then the next block of code that references it again is as follows:
...
strSQL = strSQL & vbCrLf & " SELECT cp.Contpolid, cp.CTYPE_ID, cp.C#, cp.REV, " & _
vbCrLf & "CASE WHEN cp.Div_Code = 'GM' THEN 'SLP' ELSE 'SCA' END, " & _
vbCrLf & "cp.Effective_ as EFFDATE, ADJUSTMENT, cp.terminatio, cp.TOTAL_CHG, " & _
vbCrLf & " ISNULL((SELECT SUM(isnull(t.amount, 0)) FROM transactions t " & _
vbCrLf & " WHERE cp.contpolid = t.contpolid AND t.tran_date <= '" & GRepdate & "'), 0) AS Payments, " & _
vbCrLf & " ISNULL((SELECT SUM(isnull(dirpayamt, 0)) FROM bkrtrans bkr " & _
vbCrLf & " WHERE cp.contpolid = bkr.contpolid), 0) AS BrkPayment, " & _
sStrBalance & " AS Balance, cast(0 as numeric(12,2)) as SixtyDays, cast(0 as numeric(12,2)) as NinetyDays , " & _
vbCrLf & " cast(0 as numeric(12,2)) as OverNinetyDays , CASE WHEN Register_D IS NULL THEN 'N' ELSE CASE WHEN Register_D < '" & GRepdate & "' THEN 'Y' ELSE 'N' END END "
strSQL = strSQL & vbCrLf & " FROM CONTRACTS_POLICIES cp (NOLOCK) /*JOIN Salesmen s (NOLOCK) ON s.salesmenid = cp.sales1*/ " & _
vbCrLf & " Where cp.CTYPE_ID = 1 And cp.Cancel_dat Is Null and CP.Sales1 is Not NULL " & _
vbCrLf & " AND ((CP.Effective_ <= '" & GRepdate & "' AND CP.Rev = 0) OR (CP.Adjustment <= '" & GRepdate & "' AND CP.Rev > 0)) " & _
vbCrLf & " AND NOT((" & sStrBalance & " > 0 AND cp.Effective_ <= '01/01/1996') OR (" & sStrBalance & "< 0 AND cp.Effective_ <= '01/01/1998')) " & _
vbCrLf & " And " & sStrBalance & " <> 0 "
...
What table is it even coming from? It seems like it is defined in the first block of code but isn't really a value yet.
I have connected VBA & SQL Database in order to pull information.
I have written a script that returns exactly what I want but I would like to make it dynamical (Change years used etc.) and I am here running into problems.
I need to have a special line in my SQL Query which only has 1 thing that changes between the lines (Number of lines need to change and the Case when y.Date_Year = )
I get an Error message in the below code saying that there is a Type mismatch at the " & " sign right above my "period ()" array.
Sub test()
Dim SQLDB As ADODB.Connection
Dim sQuery As String
Dim info()
Dim Start_D As String
Dim End_D As String
Dim Numerator_Used As String
Dim Denominator_Used As String
Dim Number_Years As Integer
Dim period()
Numerator_Used = Range("Numerator")
Denominator_Used = Range("Denominator")
Start_D = Range("Start_Date")
End_D = Range("End_Date")
Range("A11:J100000").Cells.ClearContents
Number_Years = End_D - Start_D
ReDim period(Number_Years + 1)
For i = 0 To Number_Years
period(i + 1) = ",sum(case when y.date_year = " & Start_D + i & " then n." & Numerator_Used & " end) / sum(case when y.date_year = " & Start_D + i & " then s." & Denominator_Used & " end) as '" & Numerator_Used & "/" & Denominator_Used & " " & Start_D + i & "' & _ "
Next i
' Get Margin Expectation Changes
sQuery ="select m.date_month" & _
" m.date_month " & _
period() & _
" from " & Numerator_Used & " as n" & _
" inner join " & Denominator_Used & " as s on s.company_id = n.company_id" & _
" and s.date_month_id = n.date_month_id" & _
" and s.date_year_id = n.date_year_id" & _
" inner join date_year as y on y.date_year_id = n.date_year_id" & _
" inner join date_month as m on m.date_month_id = n.date_month_id" & _
" where y.date_year between " & Start_D & " and " & End_D & " " & _
" and n." & Numerator_Used & " <> 0" & _
" and s." & Denominator_Used & " <> 0" & _
" group by m.date_month;"
Set rs = Common.SQL_Read(SQLDB, sQuery)
ThisWorkbook.Worksheets("Sheet1").Range("A11").CopyFromRecordset rs
Set SQLDB = Common.SQL_Close(SQLDB)
End Sub
As i mentioned in the ocmment to the question, you can not explicity convert period() data into string as it is an array of variant data type (each undefined variable is treated as variant data type). You have to loop through the array data, i.e.:
For i = LBound(period()) To UBound(period())
sQuery = sQuery & period(i) & "...."
Next
'finally:
sQuery = "SELECT ... " & sQuery & " ...."
Change the code as i mentioned above and let me know if it works.
I've got this:
sql = "INSERT INTO instroom ( " & _
"team_id, " & _
"proces_id, " & _
"datum, " & _
"aantal_instroom, " & _
"ctime, " & _
"cuser, " & _
"mtime, " & _
"muser " & _
") "
sql = sql & "SELECT " & _
"team_id, " & _
"proces_id, " & _
"datum, " & _
"SUM(aantal_instroom), " & _
"#" & Format(MTime, "yyyy-mm-dd hh:mm:ss") & "#, " & _
"" & mod_global.RealUserID & ", " & _
"#" & Format(MTime, "yyyy-mm-dd hh:mm:ss") & "#, " & _
"" & mod_global.RealUserID & " " & _
"FROM tmp_import_instroom " & _
"WHERE userid = '" & EscapeString(LCase(mod_global.RealUser)) & "' " & _
"AND team_id <> 0 " & _
"AND proces_id <> 0 "
sql = sql & "GROUP BY team_id, proces_id, datum " & _
"HAVING SUM(aantal_cases) > 0 "
When it goes through:
-- Execute Query
Private Function executeSQL(ByVal sql As String, Optional ByVal autoCommit As Boolean = False) As Boolean
On Error GoTo executeSQLError
executeSQL = False
If mod_global.DevStart Then QueryNum = QueryNum + 1
If mod_global.DevStart Then Call saveQueryToFile(sql)
' Check if database is open
If Not testConn Then
Call openDB
End If
If startTrans Then
db.Execute sql
executeSQL = True
If autoCommit Then
executeSQL = commitDB
End If
End If
DoEvents
Exit Function
executeSQLError:
Debug.Print ("executeSQL - " & Err.Number & " : " & Err.Description)
Call writeToLog("executeSQL - " & Err.Number & " : " & Err.Description)
End Function
I get the error message
"Runtime Error 3061: Too few parameters. Expected 1.".
What am I missing? I did debug.print and still can't find something wrong.
Here are my column names from tmp_import_instroom:
results of debug.print
insert into instroom (
team_id
, proces_id
, datum
, aantal_instroom
, ctime
, cuser
, mtime
, muser
)
select
team_id
, proces_id
, datum
, SUM(aantal_instroom)
, #2017-02-23 20:22:33#
, 310
, #2017-02-23 20:22:33#
, 310
from tmp_import_instroom
where userid = 'xg30222'
and team_id <> 0
and proces_id <> 0
group by team_id
, proces_id
, datum
having SUM(aantal_cases) > 0
Unless it's not showing, there's no ctime, cuser, mtime or muser in your table. Therefore, you need to alias your calculated fields.
sql = sql & "SELECT " & _
"team_id, " & _
"proces_id, " & _
"datum, " & _
"SUM(aantal_instroom) as aantal_instroom, " & _
"#" & Format(MTime, "yyyy-mm-dd hh:mm:ss") & "# as ctime, " & _
"" & mod_global.RealUserID & " as cuser, " & _
"#" & Format(MTime, "yyyy-mm-dd hh:mm:ss") & "# as mtime, " & _
"" & mod_global.RealUserID & " as muser " & _
"FROM tmp_import_instroom " & _
"WHERE userid = '" & EscapeString(LCase(mod_global.RealUser)) & "' " & _
"AND team_id <> 0 " & _
"AND proces_id <> 0 "
I'm attempting to write a domain function I can use in MS Access SQL view like what is found here: DMedian in access 2013, no values returned
...but for a DPercentile function that allows you to GROUP BY and filter.
This is what I have so far:
Public Function DPercentileWithGrpBy( _
ByVal sFld As String, _
ByVal sTable As String, _
ByVal iPercent As Integer, _
ByVal sGrpByFld As String, _
ByVal sGrpByValue As String _
) As Variant
Dim db As DAO.Database
Dim rstDomain As DAO.Recordset
Dim sSQL As String
Const errAppTypeError = 3169
On Error GoTo HandleErr
Set db = CurrentDb()
' Build SQL string for recordset.
sSQL = "SELECT " & _
sTable & "." & sGrpByFld & _
"," & (1 - iPercent / 100) & "*(" & _
"SELECT Max(" & sFld & ") " & _
"FROM " & sTable & " " & _
"WHERE " & sTable & "." & sFld & " IN (" & _
"SELECT TOP " & iPercent & " PERCENT " & sFld & " " & _
"FROM " & sTable & " " & _
"WHERE " & sTable & "." & sGrpByFld & " = " & Chr(34) & sGrpByValue & Chr(34) & " AND " & sFld & " Is Not Null ORDER BY " & sFld & ")) + " & iPercent / 100 & "*(" & _
"SELECT Min(" & sFld & ") " & _
"FROM " & sTable & " " & _
"WHERE " & sTable & "." & sFld & " IN (" & _
"SELECT TOP " & 100 - iPercent & " PERCENT " & sFld & " " & _
"FROM " & sTable & " " & _
"WHERE " & sTable & "." & sGrpByFld & " = " & Chr(34) & sGrpByValue & Chr(34) & " AND " & sFld & " Is Not Null ORDER BY " & sFld & " DESC)" & _
") AS " & iPercent & "Percentile " & _
"FROM " & sTable & " " & _
"WHERE " & sTable & "." & sGrpByFld & " = " & Chr(34) & sGrpByValue & Chr(34) & " " & _
"GROUP BY " & sTable & "." & sGrpByFld & ";"
'Debug.Print sSQL
'above should result in something like this:
'SELECT
' tblFirst250.[GICS Sector]
' , 0.75*(
' SELECT Max(GM)
' FROM tblFirst250
' WHERE tblFirst250.GM IN (
' SELECT TOP 25 PERCENT GM
' FROM tblFirst250
' WHERE tblFirst250.[GICS Sector] = "Energy" AND GM Is Not Null ORDER BY GM)) + 0.25*(
' SELECT Min(GM)
' FROM tblFirst250
' WHERE tblFirst250.GM IN (
' SELECT TOP 75 PERCENT GM
' FROM tblFirst250
' WHERE tblFirst250.[GICS Sector] = "Energy" AND GM Is Not Null ORDER BY GM DESC)
' ) AS 25Percentile
'FROM tblFirst250
'WHERE tblFirst250.[GICS Sector] = "Energy"
'GROUP BY tblFirst250.[GICS Sector];
Set rstDomain = db.OpenRecordset(sSQL, dbOpenDynaset)
DPercentileWithGrpBy = rstDomain
ExitHere:
On Error Resume Next
rstDomain.Close
Set rstDomain = Nothing
Exit Function
HandleErr:
' Return an error value.
DPercentileWithGrpBy = CVErr(Err.Number)
Resume ExitHere
End Function
I'd like to have the ability to use the function in MS Access SQL View as a query or part of a query. I also need to do a percentile (quartiles) of a sub group of records. Hopefully that make sense...
EDIT: the resulting query works when I debug.print it and using it in SQL View.
EDIT: here is how you could use it:
DPercentileWithGrpBy( "GM","tblFirst250", 25,"[GICS Sector]","Energy")