非程序员会计的SQL子查询需求:导出指定周工单关联交易数据至Excel
Solution: Using Subqueries to Pull Workorder Transaction Data for a Target Week
Hey there! As an accountant who’s dabbled in VBA and SQL, I totally get wanting to refine your queries without getting bogged down in programmer jargon. Let’s break this down into straightforward parts that fit your needs.
The Core Goal
You need to:
- Identify all workorders that had any transactions in a specified week
- Pull all related transaction data for those workorders (to calculate both weekly and cumulative amounts)
- Replace your old order-number-based logic with a subquery approach
Sample SQL Query with Subqueries
Let’s assume your database has two key tables:
Transactions: Contains individual transaction records (columns likeWorkOrderID,TransactionDate,Amount,Description)WorkOrders: Contains workorder details (optional, but useful if you need metadata like workorder names)
Here’s a query that uses a subquery to first grab the relevant workorders, then pulls all their transactions:
-- Get all transactions for workorders with activity in the target week SELECT t.WorkOrderID, wo.WorkOrderName, -- Optional: Remove if you don't have a WorkOrders table t.TransactionDate, t.Amount, t.Description, -- Calculate running cumulative amount per workorder (saves Excel work) SUM(t.Amount) OVER (PARTITION BY t.WorkOrderID ORDER BY t.TransactionDate) AS CumulativeAmount FROM Transactions t -- Join to WorkOrders if you need additional workorder details LEFT JOIN WorkOrders wo ON t.WorkOrderID = wo.WorkOrderID WHERE -- Subquery: Fetch all workorders that had at least one transaction in the target week t.WorkOrderID IN ( SELECT DISTINCT WorkOrderID FROM Transactions WHERE TransactionDate BETWEEN '2024-05-20' AND '2024-05-26' -- Replace with your week dates ) -- Sort for easier Excel formatting ORDER BY t.WorkOrderID, t.TransactionDate;
Key Breakdown:
- The subquery inside the
WHEREclause first finds every unique workorder with transactions in your specified week. This replaces any old logic that relied on hardcoding or filtering order numbers directly. - The main query pulls all transactions for those workorders—not just the ones in the week. This lets you calculate both weekly totals (filter in Excel or add a
CASEstatement in SQL) and cumulative amounts up to each transaction. - The
SUM() OVER (PARTITION BY ...)window function calculates running totals per workorder directly in SQL, so you don’t have to build those formulas manually in Excel.
Integrating with Excel VBA
Since you already know some VBA, here’s a snippet to run this query and export results to a new worksheet:
Sub ExportWeeklyWorkorderData() Dim conn As Object Dim rs As Object Dim sql As String Dim weekStart As String Dim weekEnd As String ' Set your target week (use YYYY-MM-DD format) weekStart = "2024-05-20" weekEnd = "2024-05-26" ' Build dynamic SQL query sql = "SELECT t.WorkOrderID, wo.WorkOrderName, t.TransactionDate, t.Amount, t.Description, " & _ "SUM(t.Amount) OVER (PARTITION BY t.WorkOrderID ORDER BY t.TransactionDate) AS CumulativeAmount " & _ "FROM Transactions t LEFT JOIN WorkOrders wo ON t.WorkOrderID = wo.WorkOrderID " & _ "WHERE t.WorkOrderID IN (SELECT DISTINCT WorkOrderID FROM Transactions WHERE TransactionDate BETWEEN '" & weekStart & "' AND '" & weekEnd & "') " & _ "ORDER BY t.WorkOrderID, t.TransactionDate;" ' Connect to your database (update the connection string!) Set conn = CreateObject("ADODB.Connection") conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\YourDatabase.accdb;" ' Example for Access ' Run the query Set rs = conn.Execute(sql) ' Create a new worksheet for results Dim ws As Worksheet Set ws = ThisWorkbook.Sheets.Add ws.Name = "Weekly Trans " & weekStart ' Copy column headers Dim i As Integer For i = 0 To rs.Fields.Count - 1 ws.Cells(1, i + 1).Value = rs.Fields(i).Name Next i ' Copy transaction data ws.Cells(2, 1).CopyFromRecordset rs ' Clean up connections rs.Close conn.Close Set rs = Nothing Set conn = Nothing ' Format for readability ws.Columns.AutoFit MsgBox "Data exported successfully!", vbInformation End Sub
VBA Notes:
- Replace the connection string with one that matches your database (e.g., SQL Server, Oracle, etc.). If you’re unsure, you can find your connection string by using Excel’s "From Other Sources" data import tool and copying the generated string.
- Update
weekStartandweekEndto match your target week—no need to rewrite the entire query each time.
Quick Adjustments for Your Needs
- If you only want transactions from the target week (not all historical for those workorders), move the date filter to the main query instead of the subquery. But since you need cumulative amounts, the subquery approach is better.
- If you don’t have a
WorkOrderstable, just remove theLEFT JOINline and any references towo.columns.
Hope this helps you get exactly the weekly and cumulative totals you need without the hassle of old, rigid SQL logic!
内容的提问来源于stack exchange,提问作者TouringCanary
相关产品推荐
相关产品推荐

