I have a table in SQL Server 2005 that I want to aggregate data from, here is an example.
JobName ProductionCounter StartDate EndDate CounterName Stage
----------------------------------------------------------------------------------------------------------
200 23 2012-08-30 13:45:00 Kilograms Final
200 2 2012-08-30 13:45:00 Bars Final
[...]
200 46 2012-08-30 13:45:00 2012-08-30 17:23:00 Kilograms Final
200 4 2012-08-30 13:45:00 2012-08-30 17:23:00 Bars Final
300 20 2012-08-30 13:45:00 Kilograms 1st
300 10 2012-08-30 18:12:00 Bars 1st
[...]
300 40 2012-08-30 18:12:00 2012-08-30 19:17:00 Kilograms 1st
300 20 2012-08-30 18:12:00 2012-08-30 19:17:00 Bars 1st
I want to format this into the following
JobName TotalKilos TotalBars StartDate EndDate Stage
-----------------------------------------------------------------------------------------------
200 69 6 2012-08-30 13:45:00 2012-08-30 17:23:00 Final
300 60 30 2012-08-30 18:12:00 2012-08-30 19:17:00 1st
This has made me realise I know nothing about SQL. I have tried the following as a start
SELECT JobName, SUM(ProductionCounter)
FROM vwOeeInterval
WHERE (CounterName = 'Kilos')
GROUP BY JobName
SELECT JobName, SUM(ProductionCounter)
FROM vwOeeInterval
WHERE (CounterName = 'Bars')
GROUP BY JobName
My questions are:
-
How do I combine these into one query?
-
How would I query for the columns such as
StartDateandStage? Especially where theEndDateis not filled in until the job completes?
Any pointers would be much appreciated.
Here you go:
Not sure if this
MAX(COALESCE(EndDate, 'undefined date'))works in SQL Server, since datatype’s might clash. You just need COALESCE(), when you want to replace the NULL value. If it does not work, just do MAX(EndDate) and you’re fine.