I know there are many topics on this and have been trying to read through them and get this sql to work but with no luck. I many be approaching this the wrong way so a little insight will be appreciated.
DECLARE @T AS TABLE(Machine NVARCHAR(6), Crew NVARCHAR(20), Yards DECIMAL(10,2));
INSERT INTO @T (Machine, Crew, Yards) VALUES('BL1', '1st Crew', 579.00);
INSERT INTO @T (Machine, Crew, Yards) VALUES('BL1', '2nd Crew', 0);
INSERT INTO @T (Machine, Crew, Yards) VALUES('BL4', '1st Crew', 2950.00);
INSERT INTO @T (Machine, Crew, Yards) VALUES('BL4', '2nd Crew', 1206.00);
INSERT INTO @T (Machine, Crew, Yards) VALUES('BL6', '1st Crew', 434.20);
WITH Ranked AS
(
SELECT
T.*,
rn = ROW_NUMBER() OVER (
PARTITION BY T.Crew
ORDER BY T.Crew)
FROM @T AS T
)
SELECT
R.Machine,
'1st Crew' = CASE WHEN R.Crew = '1st Crew' THEN ISNULL(R.Yards, 0) END,
'2nd Crew' = CASE WHEN R.Crew = '2nd Crew' THEN ISNULL(R.Yards, 0) END,
--'Total' = R.Yards
'Total' = CASE WHEN R.Machine = 'BL1' THEN R.Yards END
FROM Ranked AS R
GROUP BY R.Machine, R.Crew, R.Yards;
The outcome of the above script is this:
|Machine|1st Crew|2nd Crew|Total|
|BL1| 579.00| NULL| 579.00|
|BL1| NULL| 0.00| 0.00|
|BL4| 2950.00| NULL| NULL|
|BL4| NULL| 1206.00| NULL|
|BL6| 434.20| NULL| NULL|
But it should be this and I can't seem to get a total.
|Machine|1st Crew|2nd Crew|Total|
|BL1| 579.00| 0.00| 579.00|
|BL4| 2950.00| 1206.00| 4156.00|
|BL6| 434.20| NULL| 434.20|
Any suggestions? Thanks.