I have 1000 entries in a table TBL_yearlyReportwith two columns:
Date_Val (e.g. '2016-12-25 23: 48: 40.360')
Amount (e.g. 100, 1000, 100, etc.)
Sample data in TBL_yearlyReport
Date_Val | Amount
2016-12-25 | 20000
2016-02-21 | 2000
I want to see a report on the results of the year, and I want to go through a year in 2012.
The report should contain a row for each month, and the returned columns will be 4, which are weeks1, week2, week3, week4
The column value each week is the sum of the current week.
Here is what I have done so far:
DECLARE @LoopCounter INT = 1
DECLARE @MONTH INT = 1
BEGIN
WHILE(@LoopCounter <= 100)
BEGIN
SET @LoopCounter = @LoopCounter + 1
IF @MONTH = 1
BEGIN
SELECT SUM(convert(INT, amount)) as JAN,
@MONTH AS month
FROM TBL_yearlyReport
WHERE YEAR(Date_Val) = 2016 AND @MONTH = @MONTH
END
IF @MONTH = 2
BEGIN
SELECT SUM(convert(INT, amount)) as FEB,
@MONTH AS month
FROM TBL_yearlyReport
WHERE YEAR(Date_Val) = 2016 AND @MONTH = @MONTH
END
if @MONTH = 3
begin
SELECT sum(convert(int ,amount)) as FEB , @MONTH as month FROM TBL_yearlyReport
WHERE YEAR(Date_Val) = 2016 and @MONTH = @MONTH
end
/////////so on continue to
if @MONTH = 12
begin
SELECT sum(convert(int ,amount)) as FEB , @MONTH as month FROM TBL_yearlyReport
WHERE YEAR(Date_Val) = 2016 and @MONTH = @MONTH
end
if @MONTH = 12
begin
break
end
SET @MONTH = @MONTH + 1
end END
Now the problem is how to get all identifiers between the months to use BETWEEN to sum the amount?
How to get the amount on a weekly basis for each month, for example
week1 | week2 | week3 | week4
jan
feb
march
june
etc.
, ,
SELECT SUM(convert(INT, amount)) ah
FROM TBL_yearlyReport
WHERE YEAR(Date_Val) = 2016
AND id between 1 and 100
:
SELECT @WEEK1, @WEEK2, @WEEK3, @WEEK4
FROM TBL_yearlyReport
WHERE Date_Val BETWEEN @startWEEKDATE AND @EndWEEKDATE