SQL select count case comparing 2 columns - sql-server

I'm breaking my head over a SQL statement comparing 2 columns and when they are not similar the statement should add 1 to the count.
Here is my code.
SELECT
COUNT(*) CASE WHEN Column1 = Column2 THEN '0' ELSE '1' END AS result
FROM [Sheet1$]
GROUP BY Column1
What am I doing wrong? I get the error message of a missing operator in the query expression.

COUNT(*) is going to count the rows regardless of the value in result.
SUM(result) might be what you are looking for

this should do it:
SELECT
SUM(CASE WHEN Column1 = Column2 THEN 0 ELSE 1 END) AS NumberOfDiffs,
SUM(CASE WHEN Column1 = Column2 THEN 1 ELSE 0 END) AS NumberOfEquals
FROM [Sheet1$]

SELECT count(*)
WHERE NOT (Column1 = Column2)
FROM [Sheet1$]
will count how many rows don't have equal columns.

If you want the count the number of absent days from a attendance table use the following query, D1 is the first day, D2 is the second day...and so on
SELECT TOP (200) PayrollYear, PayrollMonth, EmployeeId, EmployeeName, JobNo, SUM(CASE WHEN D1 = 'A' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN D2 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D3 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D4 = 'A' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN D5 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D6 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D7 = 'A' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN D8 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D9 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D10 = 'A' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN D11 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D12 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D13 = 'A' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN D14 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D15 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D16 = 'A' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN D17 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D18 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D19 = 'A' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN D20 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D21 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D22 = 'A' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN D23 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D24 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D25 = 'A' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN D26 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D27 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D28 = 'A' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN D29 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D30 = 'A' THEN 1 ELSE 0 END) + SUM(CASE WHEN D31 = 'A' THEN 1 ELSE 0 END)
AS TotAbsent
FROM T_EmpAttendance
GROUP BY PayrollYear, PayrollMonth, EmployeeId, EmployeeName, JobNo

SELECT count(*),CASE WHEN col1=col2 THEN 'same' ELSE 'different' END AS x
FROM theTable
group by CASE WHEN col1=col2 THEN 'same' ELSE 'different' END
I am using Oracle, it do not allow me to group by x (alias name) so I am grouping by CASE statement and it works fine.

Related

Where condition a outer applied sql query

I am using a sql query but sorry to say unable to use a where condition. I post my query below.
SELECT * , CAST( RIGHT(FileNo,3) AS numeric) as IntFileNo
FROM ExportLcs A
OUTER APPLY (
SELECT SUM(ReceivedTTUsd) AS TtTotal,
SUM(ReceivedPDCUsd) AS PdcTotal,
SUM(CASE WHEN ReceivedPDCUsd > 0 THEN 1 ELSE 0 END) AS PdcCashCount,
SUM(CASE WHEN ReceivedPDCUsd > 0 THEN ConvertRate ELSE 0 END) AS PdcRateTotal,
SUM(CASE WHEN ConvertRate > 0 THEN CEILING(ReceivedPDCUsd / ConvertRate) ELSE 0 END) AS PdcTotalUsd,
Count(ExportLcId) AS TotalPaymentCount
FROM dbo.ExportPayments G
WHERE A.ExportLcId = G.ExportLcId AND (G.PdcTotal+G.PdcTotalUsd)>0
) AS G
I want to use condition like
A.ExportLcId = G.ExportLcId AND (G.PdcTotal+G.PdcTotalUsd)>0
but and part not working.
Any one can help.
How about having clause instead of where?
SELECT * , CAST(RIGHT(FileNo, 3) AS NUMERIC) AS IntFileNo
FROM dbo.ExportLcs AS A
OUTER APPLY (
SELECT SUM(ReceivedTTUsd) AS TtTotal
, SUM(ReceivedPDCUsd) AS PdcTotal
, SUM(CASE WHEN ReceivedPDCUsd > 0 THEN 1 ELSE 0 END) AS PdcCashCount
, SUM(CASE WHEN ReceivedPDCUsd > 0 THEN ConvertRate ELSE 0 END) AS PdcRateTotal
, SUM(CASE WHEN ConvertRate > 0 THEN CEILING(ReceivedPDCUsd / ConvertRate) ELSE 0 END) AS PdcTotalUsd
, COUNT(ExportLcId) AS TotalPaymentCount
FROM dbo.ExportPayments AS G
WHERE A.ExportLcId = G.ExportLcId
HAVING (SUM(ReceivedPDCUsd) + SUM(CASE WHEN ConvertRate > 0 THEN CEILING(ReceivedPDCUsd / ConvertRate) ELSE 0 END)) > 0
) AS G;
You should consider using Outer Join instead, so try the following:
SELECT * , CAST( RIGHT(FileNo,3) AS numeric) as IntFileNo from ExportLcs A left outer join
(
SELECT SUM(ReceivedTTUsd) AS TtTotal,
SUM(ReceivedPDCUsd) AS PdcTotal,
SUM(CASE WHEN ReceivedPDCUsd > 0 THEN 1 ELSE 0 END) AS PdcCashCount,
SUM(CASE WHEN ReceivedPDCUsd > 0 THEN ConvertRate ELSE 0 END) AS PdcRateTotal,
SUM(CASE WHEN ConvertRate > 0 THEN CEILING(ReceivedPDCUsd / ConvertRate) ELSE 0 END) AS PdcTotalUsd,
Count(ExportLcId) AS TotalPaymentCount
FROM dbo.ExportPayments) G
on A.ExportLcId = G.ExportLcId where (G.PdcTotal+G.PdcTotalUsd)>0
just put your part where clause outside.
SELECT * , CAST( RIGHT(FileNo,3) AS numeric) as IntFileNo
FROM Export
where (G.PdcTotal+G.PdcTotalUsd)>0Lcs A
OUTER APPLY (
SELECT SUM(ReceivedTTUsd) AS TtTotal,
SUM(ReceivedPDCUsd) AS PdcTotal,
SUM(CASE WHEN ReceivedPDCUsd > 0 THEN 1 ELSE 0 END) AS PdcCashCount,
SUM(CASE WHEN ReceivedPDCUsd > 0 THEN ConvertRate ELSE 0 END) AS PdcRateTotal,
SUM(CASE WHEN ConvertRate > 0 THEN CEILING(ReceivedPDCUsd / ConvertRate) ELSE 0 END) AS PdcTotalUsd,
Count(ExportLcId) AS TotalPaymentCount
FROM dbo.ExportPayments G
WHERE A.ExportLcId = G.ExportLcId
) AS G

unpivot one row of aggregates to 1 column

I have this query that returns 1 row of aggregate sums
DECLARE #Income9 int
SELECT #Income9 = IncomeLevel FROM PovertyLevels WHERE HouseholdNumber = 9
;WITH CTE
AS
(
SELECT PatientProfileID, CASE WHEN v.FamilyMembersinHousehold > 8
THEN ROUND((CAST(AnnualIncome as float)/(CAST(#Income9 as float) +((V.FamilyMembersinHousehold-8)* CAST(#Income9 as Float)))*100.00), 5)
WHEN ((v.FamilyMembersinHousehold IS NULL) OR (AnnualIncome IS NULL)) THEN NULL
ELSE ROUND(((CAST(AnnualIncome AS Float)/CAST(pl.IncomeLevel as Float)) * 100.00), 5) END AS PercentOfPoverty
FROM vPatientDemographics v
LEFT OUTER JOIN PovertyLevels pl ON v.FamilyMembersinHousehold = pl.HouseholdNumber
)
SELECT SUM(CASE WHEN PercentOfPoverty <= 100 THEN 1 ELSE 0 END) AS NumOfPatientsBelow100,
SUM(CASE WHEN PercentOfPoverty BETWEEN 101 AND 150 THEN 1 ELSE 0 END) AS NumOfPatientsBetween101And150,
SUM(CASE WHEN PercentOfPoverty BETWEEN 151 AND 200 THEN 1 ELSE 0 END) AS NumOfPatientsBetween151And200,
SUM(CASE WHEN PercentOfPoverty > 200 THEN 1 ELSE 0 END) AS NumOfPatientsOver200,
SUM(CASE WHEN PercentOfPoverty IS NULL THEN 1 ELSE 0 END) AS NumOfPatientsUnknown
FROM CTE
I would like to have the sum data to be in rows not columns.
I tried adding this UNPIVOT but it does not recognize the column names.
UNPIVOT
(
Levels for PovertyLevels in (NumOfPatientsBelow100, NumOfPatientsBetween101And150, NumOfPatientsBetween151And200,
NumOfPatientsOver200, NumOfPatientsUnknown)
) as Unpvt
How can I unpivot the initial data set to that it is in rows not columns?
It is because Where clause is evaluated before the select
SELECT #Income9 = IncomeLevel FROM PovertyLevels WHERE HouseholdNumber = 9
;WITH CTE
AS
(
SELECT PatientProfileID, CASE WHEN v.FamilyMembersinHousehold > 8
THEN ROUND((CAST(AnnualIncome as float)/(CAST(#Income9 as float) +((V.FamilyMembersinHousehold-8)* CAST(#Income9 as Float)))*100.00), 5)
WHEN ((v.FamilyMembersinHousehold IS NULL) OR (AnnualIncome IS NULL)) THEN NULL
ELSE ROUND(((CAST(AnnualIncome AS Float)/CAST(pl.IncomeLevel as Float)) * 100.00), 5) END AS PercentOfPoverty
FROM vPatientDemographics v
LEFT OUTER JOIN PovertyLevels pl ON v.FamilyMembersinHousehold = pl.HouseholdNumber
),intr as
(
SELECT SUM(CASE WHEN PercentOfPoverty <= 100 THEN 1 ELSE 0 END) AS NumOfPatientsBelow100,
SUM(CASE WHEN PercentOfPoverty BETWEEN 101 AND 150 THEN 1 ELSE 0 END) AS NumOfPatientsBetween101And150,
SUM(CASE WHEN PercentOfPoverty BETWEEN 151 AND 200 THEN 1 ELSE 0 END) AS NumOfPatientsBetween151And200,
SUM(CASE WHEN PercentOfPoverty > 200 THEN 1 ELSE 0 END) AS NumOfPatientsOver200,
SUM(CASE WHEN PercentOfPoverty IS NULL THEN 1 ELSE 0 END) AS NumOfPatientsUnknown
FROM CTE
)
Select cnt,range from intr
cross apply (values (NumOfPatientsBelow100,'NumOfPatientsBelow100'),
(NumOfPatientsBetween101And150,'NumOfPatientsBetween101And150'),
(NumOfPatientsBetween151And200,'NumOfPatientsBetween151And200'),
(NumOfPatientsOver200,'NumOfPatientsOver200'),
(NumOfPatientsUnknown,'NumOfPatientsUnknown')) cs (cnt,range)

SQL procedure sum and sum inside select and insert to

I have a little problem. I have a insert into block with select and inside select I have sum. Thats works well. But In this select I need also do some operation on these sums. I don't know how.
Code:
insert into [dbo].[DiscountDailyStatsTemp]
SELECT
#DiscountId,
cast([dbo].[TelemetryData].[EventTime] as date) as 'Date',
sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountLike' then 1 else 0 end) as 'Likes',
sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountDislike' then 1 else 0 end) as 'Dis likes',
sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountShare' then 1 else 0 end) as 'Shares',
SUM(case when [dbo].[TelemetryData].[EventName]='DiscountView' then 1 else 0 end) as 'Views',
SUM(case when [dbo].[TelemetryData].[EventName]='DiscountClick' then 1 else 0 end) as 'Clicks',
Sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountCode' then 1 else 0 end) as 'Downloaded codes',
Sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountSave' then 1 else 0 end) as 'Saves',
sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountClickWWW' then 1 else 0 end) as 'Page redirections',
0 as 'Average CTR',
#UniqueUsers as 'Unique users',
#NewUsers as 'New users',
#ReturningUsers as 'Returning users',
Sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountCommentPositive' then 1 else 0 end) as 'Positive comments',
sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountCommentNegative' then 1 else 0 end) as 'Negative comments'
from [dbo].[TelemetryData]
where [dbo].[TelemetryData].[DiscountId] = #DiscountId
and ([dbo].[TelemetryData].[EventName] = 'DiscountView' or [dbo].[TelemetryData].[EventName] = 'DiscountClick' or
[dbo].[TelemetryData].[EventName] = 'DiscountDislike' or [dbo].[TelemetryData].[EventName] = 'DiscountCode' or
[dbo].[TelemetryData].[EventName] = 'DiscountLike' or [dbo].[TelemetryData].[EventName] = 'DiscountShare' or
[dbo].[TelemetryData].[EventName] = 'DiscountClickWWW' or [dbo].[TelemetryData].[EventName] = 'DiscountSave' or
[dbo].[TelemetryData].[EventName] = 'DiscountCommentPositive' or [dbo].[TelemetryData].[EventName] = 'DiscountCommentNegative')
group by cast([dbo].[TelemetryData].[EventTime] as date)
order by cast([dbo].[TelemetryData].[EventTime] as date) asc
And look there is 0 as 'Average CTR' I need to change it for this:
Round(cast('Clicks' as float) / cast(case when 'Views' = 0 then 1 else 'Views') end as float) * 100, 2) as 'Average CTR',
But it not working. How I can do it?
You can't use the aliases in the same level they are created, and also this is a query with a group by clause, which means each column should be either in the group by or with an aggregation function around it.
You can wrap your query with another select :
SELECT [date],
[likes],
....
Round(cast([Clicks] as float) / cast(case when [Views] = 0 then 1 else [Views] end) as float) * 100, 2) as [Average CTR],
FROM(YOUR QUERY HERE)
Also, use square brackets for columns name.

SQL Pivot from an Access Pivot query

I have the following Access query that needs turned into SQL -
TRANSFORM
Sum([anaes_downtime]![ANAESENDTIME]-[anaes_downtime]![anaesstarttime])/24/60 AS Expr1
SELECT downtime_seq.THEATRE, downtime_seq.OPSESSION, downtime_seq.OPDATE
FROM ANAES_Downtime
INNER JOIN downtime_seq ON ANAES_Downtime.opnumber = downtime_seq.opnumber
WHERE (((ANAES_Downtime.ANAESSTARTTIME) <> 0 )
AND ((ANAES_Downtime.ANAESENDTIME) <> 0 ))
GROUP BY downtime_seq.THEATRE, downtime_seq.OPSESSION, downtime_seq.OPDATE
PIVOT "d" & [opseq] IN ("d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","d10","d11","d12","d13","d14","d15","d16","d17","d18","d19","d20");
I understand the basics of sql pivot but have been unable to convert this successfully. Any help?
I have found an answer to my question using the CASE statement -
SELECT ad.THEATRE, ad.OPSESSION, ad.OPDATE,
SUM(CASE WHEN opseq = 0
THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd0',
SUM(CASE WHEN opseq = 1
THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd1',
SUM(CASE WHEN opseq = 2
THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd2',
SUM(CASE WHEN opseq = 3
THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd3',
SUM(CASE WHEN opseq = 4
THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd4',
SUM(CASE WHEN opseq = 5
THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd5'...
...FROM #ANAES_Downtime ad INNER JOIN #DowntimeSeq ds ON ad.opnumber = ds.opnumber
WHERE ad.ANAESSTARTTIME <> 0 AND ad.ANAESENDTIME <> 0
GROUP BY ad.THEATRE, ad.OPSESSION, ad.OPDATE
ORDER BY ad.THEATRE, ad.OPSESSION, ad.OPDATE

Grouping Records by header SQL

I have the following query;
SELECT STOCK_CODE,
dbo.manu_STOCK.DESCRIPTION,
QTY_IN_STOCK,
Quantity,
ForecastDate
FROM [FS25-w2k8\SQLEXPRESS].sagel50_46772.dbo.SalesForecastLines AS SalesForecastLines1
INNER JOIN dbo.manu_STOCK
ON SalesForecastLines1.ProductCode = dbo.manu_STOCK.STOCK_CODE
This brings up the following information;
STOCK_CODE DESCRIPTION QTY_INSTOCK Quantity ForecastDate
523 gel 12 10 01/08/2014
523 gel 12 10 08/08/2014
I want to be able to modify the query so that it displays the following formation
Stock Code Description WK1 WK2
523 gel 22 22
So it will sum qty in stock and quantity on the first date and the column will be called wk1, second week - wk2 etc.
Can you advise on this please?
IF you want to pivot the results for 52 weeks, you can use the following query. This will pivot data for 52 weeks. This is just concept, I could not test this query.
SELECT * FROM
( SELECT
dbo.manu_STOCK.STOCK_CODE AS [Stock Code],
dbo.manu_STOCK.DESCRIPTION,
DATEPART(WEEK,[Date]) Wk,
QTY_IN_STOCK + Quantity AS Stock
FROM [FS25-w2k8\SQLEXPRESS].sagel50_46772.dbo.SalesForecastLines AS SalesForecastLines1
INNER JOIN dbo.manu_STOCK
ON SalesForecastLines1.ProductCode = dbo.manu_STOCK.STOCK_CODE
) AS Source
PIVOT
(
SUM(Stock)
FOR WK IN
([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]
,[11],[12],[13],[14],[15],[16],[17],[18],[19],[20]
,[21],[22],[23],[24],[25],[26],[27],[28],[29],[30]
,[31],[32],[33],[34],[35],[36],[37],[38],[39],[40]
,[41],[42],[43],[44],[45],[46],[47],[48],[49],[50]
,[51],[52])
) AS PVT ;
DECLARE #Stock TABLE
(
STOCK_CODE INT,
DESCRIPTION VARCHAR(50),
QTY_INSTOCK INT,
QUANTITY INT,
FORECASTDATE DATETIME
)
INSERT INTO #Stock
( STOCK_CODE, DESCRIPTION, QTY_INSTOCK, QUANTITY, FORECASTDATE )
VALUES
( 523, 'gel', 12, 10, '01/08/2014' ),
( 523, 'gel', 12, 10, '08/08/2014' )
SELECT
s.STOCK_CODE,
s.DESCRIPTION,
s.STOCKYEAR,
SUM(CASE WHEN s.STOCKWEEK = 1 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk1,
SUM(CASE WHEN s.STOCKWEEK = 2 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk2,
SUM(CASE WHEN s.STOCKWEEK = 3 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk3,
SUM(CASE WHEN s.STOCKWEEK = 4 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk4,
SUM(CASE WHEN s.STOCKWEEK = 5 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk5,
SUM(CASE WHEN s.STOCKWEEK = 6 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk6,
SUM(CASE WHEN s.STOCKWEEK = 7 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk7,
SUM(CASE WHEN s.STOCKWEEK = 8 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk8,
SUM(CASE WHEN s.STOCKWEEK = 9 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk9,
SUM(CASE WHEN s.STOCKWEEK = 10 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk10,
SUM(CASE WHEN s.STOCKWEEK = 11 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk11,
SUM(CASE WHEN s.STOCKWEEK = 12 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk12,
SUM(CASE WHEN s.STOCKWEEK = 13 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk13,
SUM(CASE WHEN s.STOCKWEEK = 14 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk14,
SUM(CASE WHEN s.STOCKWEEK = 15 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk15,
SUM(CASE WHEN s.STOCKWEEK = 16 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk16,
SUM(CASE WHEN s.STOCKWEEK = 17 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk17,
SUM(CASE WHEN s.STOCKWEEK = 18 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk18,
SUM(CASE WHEN s.STOCKWEEK = 19 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk19,
SUM(CASE WHEN s.STOCKWEEK = 20 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk20,
SUM(CASE WHEN s.STOCKWEEK = 21 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk21,
SUM(CASE WHEN s.STOCKWEEK = 22 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk22,
SUM(CASE WHEN s.STOCKWEEK = 23 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk23,
SUM(CASE WHEN s.STOCKWEEK = 24 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk24,
SUM(CASE WHEN s.STOCKWEEK = 25 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk25,
SUM(CASE WHEN s.STOCKWEEK = 26 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk26,
SUM(CASE WHEN s.STOCKWEEK = 27 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk27,
SUM(CASE WHEN s.STOCKWEEK = 28 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk28,
SUM(CASE WHEN s.STOCKWEEK = 29 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk29,
SUM(CASE WHEN s.STOCKWEEK = 30 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk30,
SUM(CASE WHEN s.STOCKWEEK = 31 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk31,
SUM(CASE WHEN s.STOCKWEEK = 32 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk32,
SUM(CASE WHEN s.STOCKWEEK = 33 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk33,
SUM(CASE WHEN s.STOCKWEEK = 34 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk34,
SUM(CASE WHEN s.STOCKWEEK = 35 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk35,
SUM(CASE WHEN s.STOCKWEEK = 36 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk36,
SUM(CASE WHEN s.STOCKWEEK = 37 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk37,
SUM(CASE WHEN s.STOCKWEEK = 38 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk38,
SUM(CASE WHEN s.STOCKWEEK = 39 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk39,
SUM(CASE WHEN s.STOCKWEEK = 40 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk40,
SUM(CASE WHEN s.STOCKWEEK = 41 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk41,
SUM(CASE WHEN s.STOCKWEEK = 42 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk42,
SUM(CASE WHEN s.STOCKWEEK = 43 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk43,
SUM(CASE WHEN s.STOCKWEEK = 44 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk44,
SUM(CASE WHEN s.STOCKWEEK = 45 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk45,
SUM(CASE WHEN s.STOCKWEEK = 46 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk46,
SUM(CASE WHEN s.STOCKWEEK = 47 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk47,
SUM(CASE WHEN s.STOCKWEEK = 48 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk48,
SUM(CASE WHEN s.STOCKWEEK = 49 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk49,
SUM(CASE WHEN s.STOCKWEEK = 50 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk50,
SUM(CASE WHEN s.STOCKWEEK = 51 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk51,
SUM(CASE WHEN s.STOCKWEEK = 52 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk52,
SUM(CASE WHEN s.STOCKWEEK = 53 THEN s.QTY_INSTOCK + s.QTY ELSE 0 END) Wk53
FROM
(
SELECT s.STOCK_CODE, s.DESCRIPTION, DATEPART(YEAR, s.FORECASTDATE) STOCKYEAR, DATEPART(WEEK, s.FORECASTDATE) STOCKWEEK, SUM(s.QTY_INSTOCK) QTY_INSTOCK, SUM(s.QUANTITY) QTY
FROM #Stock s
GROUP BY s.STOCK_CODE, s.DESCRIPTION, DATEPART(YEAR, s.FORECASTDATE), DATEPART(WEEK, s.FORECASTDATE)
) s
GROUP BY s.STOCK_CODE, s.DESCRIPTION, s.STOCKYEAR
ORDER BY s.STOCK_CODE, s.DESCRIPTION, s.STOCKYEAR
Group by the code, desc, year and week and then sum by week for each week of the year (adding extra week depending on day beginning / end of the year falls.

Resources