Reckon this'll get it:
Public Sub QueryTextFile()
Dim rsData As ADODB.Recordset
Dim sConnect As String
Dim sSQL As String
Dim lngLastRow As Long
Dim strStartDate As String
Dim strEndDate As String
strStartDate = "01/01/2015"
strEndDate = "01/31/2015"
' Create the connection string.
sConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.Path & "\;" & "Extended Properties=Text;"
' Create the SQL statement.
sSQL = "SELECT PRODUCT_ID,'" & _
strStartDate & "-" & strEndDate & _
"', WH, Sum(AMOUNT), SUM(AMOUNT)/(SELECT SUM(AMOUNT) FROM sample.txt WHERE DAY >=#" & strStartDate & "# And DAY<=#" & strEndDate & "#)" & _
"FROM sample.txt " & _
"WHERE DAY >=#" & strStartDate & "# And DAY<=#" & strEndDate & "# " & _
"Group By WH,PRODUCT_ID;"
Debug.Print
Set rsData = New ADODB.Recordset
rsData.Open sSQL, sConnect, adOpenForwardOnly, adLockReadOnly, adCmdText
' Check to make sure we received data.
If Not rsData.EOF Then
' Dump the returned data onto Sheet1.
Range("A1").CopyFromRecordset rsData
Else
MsgBox "No records returned.", vbCritical
End If
' Clean up our Recordset object.
rsData.Close
End Sub
Not the best performance wise (might still be better with formula on a large dataset)
SQL:
SELECT product_id,
'01/01/2015-01/31/2015',
wh,
SUM(amount),
SUM(amount) / (SELECT SUM(amount)
FROM sample.txt
WHERE day >=# 01/01/2015#
AND day <=# 01/31/2015#)
FROM sample.txt
WHERE day >=# 01/01/2015#
AND day <=# 01/31/2015#
GROUP BY wh,
product_id;
Bookmarks