I’m a CTO for a small manufacturing firm, obviously doing some very hands on stuff and am grateful to experts out there providing their time to people less experienced.
I’m trying to construct a query for SQL Server to aggregate time for each machine in a manufacturing process.
The results I get look something like:
InvoiceID Min DateIn MachineName MachineID
17993 12 2012-09-28 Beam Saw 1
17993 26 2012-09-28 Beam Saw 1
17993 17 2012-10-02 Edge Banding 3
17993 21 2012-10-02 Skipper 4
17993 23 2012-10-03 Shipping 5
etc for next invoice.
My code:
SELECT i.InvoiceID
,SUM(DATEPART(Minute,(wf.DateTimeOut - wf.DateTimeIn))) AS [Min]
,CAST(wf.DateTimeIn AS DATE) AS [DateIn]
,m.MachineName
,wf.MachineID
FROM Workflow wf
JOIN
InvoicesPerJobPeriod ipjp
ON
ipjp.Workflowid = wf.ID
JOIN Machines m
ON
m.MachineID = wf.MachineID
JOIN
Invoices i
ON ipjp.InvoiceID = i.InvoiceID
WHERE (i.InActive = '0')
GROUP BY i.InvoiceID, m.MachineName, wf.MachineID, wf.DateTimeIn
ORDER BY i.InvoiceID, wf.MachineID
I don’t understand why the grouping shows multiple records for the Beam Saw. Ideally, there should be one record per machine, per invoice. The Datetimein is usually going to be the same day, but I need to display it, just in case a manufacturing step spans days. In that case I would reasonable to have multiple records for a machine.
Thank you so much for your help. It’s greatly appreciated.
Cliff
If
wf.DateTimeInis different at all (in either the date or the time components) for two different Beam Saw records, they will generate separate lines in theGROUP BYclause, even though your non-aggregated usage in theSELECTstatement is only referring to the date portion.If what you want is to group by the date portion of
DateTimeInonly, you should write something like this:This will ensure that any number of Beam Saw records that otherwise match and are entered on the same date will be grouped together into a single row.
However, this may change the semantics of your aggregate statement, so you’ll need to verify the query works as you desire after you make this change.