The following is my query to go through about a million rows to calculate MTBUR (Mean Time Before Unscheduled Repair):
DECLARE @BeginDate date = '01-01-2013',
@EndDate date = '12-31-2013'
BEGIN
SELECT H.AutoType,
COALESCE(((SUM(H.Hours))/(CASE WHEN R.ReceivedDate BETWEEN @BeginDate AND @EndDate THEN COUNT(R.Confirmed) END)), SUM(H.Hours)) AS 'MTBUR'
FROM Hours H
INNER JOIN Repair R
ON H.SN = R.SN
WHERE (R.Confirmed NOT LIKE 'C%' AND R.Confirmed NOT LIKE 'O%')
AND (H.Date BETWEEN @BeginDate AND @EndDate)
GROUP BY H.AutoType,
R.ReceivedDate
END
The following are example results for 2 types:
Type | MTBUR
------------
a | value
a | value
a | value
b | value
b | value
b | value
I want my results to look like this:
Type | MTBUR
------------
a | value
b | value
Why is it grouping the same type several times. I want only 1 value for each type.
Also, Why is the DBMS making me also group by ReceivedDate? I get the feeling that is screwing my results up. Any suggestions?
The following are my CREATE TABLE:
CREATE TABLE [dbo].[acss_hours](
[hoursId] [uniqueidentifier] NOT NULL,
[name] [nvarchar](100) NULL,
[Type] [nvarchar](100) NULL,
[SN] [nvarchar](100) NULL,
[Reg] [nvarchar](100) NULL,
[Hours] [float] NULL,
[Date] [datetime] NULL)
CREATE TABLE [dbo].[repair](
[repairId] [uniqueidentifier] NOT NULL,
[Part] [nvarchar](100) NULL,
[Customer] [nvarchar](100) NULL,
[AutoType] [nvarchar](100) NULL,
[ReceivedDate] [datetime] NULL,
[Confirmed] [nvarchar](100) NULL,
[Company] [nvarchar](100) NULL,
[Reg] [nvarchar](100) NULL,
[Manu] [nvarchar](100) NULL,
[SN] [nvarchar](100) NULL)