Calculate YTD, Previous YTD in the same query - sql

How could I calculate to calculate YTD and prior YTD in the same query?
I try to calculate weight and weight ytd. I didn't undestand how to add the calculation of prior ytd in the same query.
YTD: Sum Weight from the first of January to today
prior YTD: Sum
Weight from the first of January of last year to today minus 1 year
SELECT SUM(CASE
WHEN convert(date,s.Delivery_Year+'-'+ s.Delivery_month+'-'+ s.Delivery_day) BETWEEN dateadd(yy, DATEDIFF(yy, 0, GETDATE()), 0) AND GETDATE() THEN s.Weight
ELSE 0
END) AS WeightYTD ,
sum(Weight) AS weight ,
[Sales_Organization] ,
[Market_Grp] ,
[Delivery_Year] ,
[Delivery_month] ,
Delivery_day
FROM Fact_sales s
GROUP BY ,
[Sales_Organization] ,
[Market_Grp] ,
[Delivery_Year] ,
[Delivery_month] ,
Delivery_day

It's still quite unclear as to what results/behaviour you actually want.
One possible interpretation is that the "year to date" is relative to the date in the table, and not relative to "today" / GETDATE().
So...
for 14th March 2018 : YTD = 1st Jan 2018 to 14th March 2018
for 20th March 2019 : YTD = 1st Jan 2019 to 20th March 2019
That being the case, I would do the following to get the YTD column...
WITH
grouped_by_date AS
(
SELECT
[Sales_Organization],
[Market_Grp],
[Delivery_Year],
[Delivery_Month],
[Delivery_Day],
SUM([Weight]) AS Weight
FROM
Fact_sales s
GROUP BY
[Sales_Organization],
[Market_Grp],
[Delivery_Year],
[Delivery_Month],
[Delivery_Day]
),
cumulative_sum_for_ytd AS
(
SELECT
*,
SUM([Weight]) OVER (PARTITION BY [Delivery_Year]
ORDER BY [Delivery_Month], [Delivery_Day]
)
AS Weight_YTD
FROM
grouped_by_date
),
There isn't a LAG() function in SQL Server 2008, but there are "hacky tricks" that can simulate it...
hack_to_do_lag AS
(
SELECT
*,
CASE
WHEN [Delivery_Year]%2=1
THEN MAX(CASE WHEN [Delivery_Year]%2=0 THEN [Weight_YTD] END) OVER (PARTITION BY ([Delivery_Year]+0)/2)
ELSE MAX(CASE WHEN [Delivery_Year]%2=1 THEN [Weight_YTD] END) OVER (PARTITION BY ([Delivery_Year]+1)/2)
END
AS Weight_PreviousYTD
FROM
cumulative_sum_for_ytd
)
SELECT
*
FROM
hack_to_do_lag

Related

subtract two rows which are result of group bc clause

I am having a case where I have raw data I am grouping it according to year and then I have to subtract the year to get the value but it is not working. example data is
year, profit,gross
2020 252563.02E9 352563.02E9
2022 102563.02E9 352563.02E9
2021 352563.02E9 352563.02E9
2022 482563.02E9 352563.02E9
2021 002563.02E9 352563.02E9
2020 10231.02E9 352563.02E9
2022 345633.25E9 352563.00E9
with
cal as
(
SELECT t.year,
cast(sum(t.profit) as decimal(17,2)) profit ,
cast(sum(t.gross)as decimal(17,2)) gross
-- t.srad_agency_provision - LAG(t.srad_agency_provision) OVER(ORDER BY year) as diff_previous_year
from shoptable t
group by t.year
order by t.year
)
after this query I got following result
year profit gross
2020 22311834.85 1030294447.42
2021 26598154.02 1704662197.69
2022 25234347.02 1841593955.36
Now I want to subtract the profit and gross from previos one.like 2021 from 2022, 2020 from 2021 I am trying
diff as (
select
t.year,
t.profit,
(t.profit) - LAG(t.profit) OVER(ORDER BY year) as diff_profit
from
shop table t
)
but it is showing for whole each value in 2020 and so on. I want to subtract the results of group by clause which I got in previous query.
Expected output is
year profit gross diff_profit diff gross
2020 22311834.85 1030294447.42 4,286,319.17 674,367,750.27
2021 26598154.02 1704662197.69 -1363807 136,931,757.67
2022 25234347.02 1841593955.36
How can I achieve it?thank you
Should not you just apply you window function to the results of cal. Something along this lines:
-- sample data
with dataset(year, profit,gross) as (
values
('2020', 252563, 352563),
('2022', 102563, 352563),
('2021', 352563, 352563),
('2022', 482563, 352563),
('2021', 002563, 352563),
('2020', 10231 , 352563),
('2022', 345633, 352563)
),
cal as (
SELECT t.year,
sum(t.profit) profit ,
sum(t.gross) gross
from dataset t
group by t.year
order by t.year
)
-- query
select *,
(profit) - LAG(profit) OVER(ORDER BY year) as diff_profit,
(gross) - LAG(gross) OVER(ORDER BY year) as diff_gross
from cal;

How to Show Previous Year on Dynamic Date

I have a database that has customer, product, date and volume/revenue data. I'd like to create two NEW columns to show the previous year volume and revenue based on the date/customer/product.
I've tried unioning two views, one that has dates (unchanged) and a second view that creates a CTE where I select the dates minus one year with another select statement off of that where VOL and REV are renamed VOL_PY and REV_PY but the data is incomplete. Basically what's happening is the PY data is only pulling volume and revenue if there is data in the prior year (for example if a customer didn't sell a product in 2021 but DID in 2020, it wouldn't pull for the VOL_PY for 2020 - because it didn't sell in 2021). How do I get my code to include matches in dates but also the instances where there isn't data in the "current" year?
Here's what I'm going for:
[EXAMPLE DATA WITH NEW COLUMNS]
CURRENT YEAR VIEW:
SELECT
CUSTOMER
,PRODUCT
,DATE
,VOL
,REV
,0 AS VOL_HL_PY
,0 AS REV_DOLS_PY
,DATEADD(YEAR, -1, DATE) AS DATE_PY FROM dbo.vwReporting
PREVIOUS YEAR VIEW:
WITH CTE_PYFIGURES
([AUTONUMBER]
,CUSTOMER
,PRODUCT
,DATE
,VOL
,REV
,DATE_PY
) AS
(
SELECT b.*
, DATEADD(YEAR, 1, DATE) AS DATE_PY
FROM dbo.basetable b
)
SELECT
v.CUSTOMER
,v.PRODUCT
,v.DATE
,0 AS v.VOL
,0 AS v.REV
,CTE.VOL_HL AS VOL_HL_PY
,CTE.REV_DOLS AS REV_DOLS_PY
,DATEADD(YEAR,-1,CTE.PERIOD_DATE_PY) AS PERIOD_DATE_PY
FROM dbo.vwReporting AS v
FULL OUTER JOIN CTE_PYFIGURES AS CTE ON CTE.CUSTOMER=V.CUSTOMER AND CTE.PRODUCT=V.PRODCUT AND CTE.DATE_PY=V.DATE
You need to offset your current year's data to one year forward and then union it with the current data, placing zeroes for "other" measures (VOL and REV for previous year and VOL_PY and REV_PY for current year). Then do aggregation. This way you'll have all the dimensions' values that were in current or previous year.
with a as (
select
CUSTOMER
, PRODUCT
, [DATE]
, VOL
, REV
, 0 as vol_py
, 0 as rev_py
from dbo.vwReporting
union all
select
CUSTOMER
, PRODUCT
, dateadd(year, 1, [DATE]) as [DATE]
, 0 as VOL
, 0 as REV
, vol as vol_py
, rev as rev_py
from dbo.vwReporting
)
select
CUSTOMER
, PRODUCT
, [DATE]
, VOL
, sum(vol) as vol
, sum(rev) as rev
, sum(vol_py) as vol_py
, sum(rev_py) as rev_py
from a
group by
CUSTOMER
, PRODUCT
, [DATE]
, VOL

SQL Get Quarter over Quarter values

I'd Like to get QoQ from a dataset with Q3 and Q4 data that also has a report date column, each row should have a QoQ value for each fiscal month (represented by a report date), Q4 should compare against Q3 but my statement only seems to be comparing within the same quarter i.e. Q4 is comparing against Q4 instead of Q4 comparing to Q3 ..
I am using the lag function but not sure what I am doing wrong if someone could please see code below.
SELECT [Year],
[SalesDate] as Report_Date,
[Quarter],
Sales,
LAG(Sales, 1, 0) OVER(
PARTITION BY [Year] ,[Quarter]
ORDER BY [Year],
[Quarter],
salesDate
ASC) AS [QuarterSales_Offset],
sales - LAG(Sales) OVER(
PARTITION BY [Year] ,[Quarter]
ORDER BY [Year],
[Quarter],
salesDate
ASC) as diff,
Case When
LAG(Sales,1,0) OVER(
PARTITION BY [Year],[Quarter]
ORDER BY [Year],
[Quarter],
salesDate
ASC) = 0 then null else
(
sales - LAG(Sales,1,0) OVER(
PARTITION BY [Year],[Quarter]
ORDER BY [Year],
[Quarter],
salesDate
ASC))/ LAG(Sales,1,0) OVER(
PARTITION BY [Year],[Quarter]
ORDER BY [Year],
[Quarter],
salesDate
ASC) end as QoQ
FROM dbo.ProductSales_2;
Query Output:
Since LAG() at 1 offset returns previous row and your data is at month level, you actually compare month over month in each quarter. Consider a different approach such as joining two subsets of your data by quarter and month in quarter.
QuarterMonth column can be calculated with ROW_NUMBER() expression (i.e., running count of months within each quarter). Since month gaps in sales data can potentially arise, use a year_quarter_month calendar table aligned to your fiscal year. Altogether, this allows comparison of first FY Q4 month (2020-08-31) to first FY Q3 month (2020-05-31) by columns.
WITH unit AS (
SELECT yqm.[Year]
, yqm.[Quarter]
, yqm.[Month]
, COALESCE(p.[Report_Date], DATEADD(DAY, -1, DATEFROMPARTS(yqm.[Year], yqm.[Month]+1, 1))) AS [Report_Date]
, p.[Sales]
FROM year_quarter_month_table yqm
LEFT JOIN dbo.ProductSales_2 p
ON yq.[Year] = p.[Year]
AND yq.[Quarter] = p.[Quarter]
AND yq.[Month] = p.[Month]
), sub AS (
SELECT [Year]
, [Quarter]
, [Month]
, ROW_NUMBER() OVER(PARTITION BY [Year], [Quarter]
ORDER BY [Report_Date]) AS [QuarterMonth]
, [Report_Date]
, [Sales]
FROM unit
)
SELECT q4.[Year]
, q4.[Report_Date] AS Q4_Date
, q4.[Sales] AS Q4_Sales
, q3.[Report_Date] AS Q3_Date
, q3.[Sales] AS Q3_Sales
, q4.[Sales] - q3.[Sales] AS Diff
, COALESCE((q4.[Sales] - q3.[Sales]) / q3.[Sales], 0) AS QoQ
FROM sub q4
LEFT JOIN sub q3
ON q4.[Year] = q3.[Year]
AND q4.[Quarter] = 4
AND q3.[Quarter] = 3
AND q4.[QuarterMonth] = q3.[QuarterMonth]
You may be able to generalize to any quarter-over-quarter calculation and not just Q3 and Q4:
WITH sub AS (
-- SAME CTEs AS ABOVE
)
SELECT curr_qtr.[Year]
, curr_qtr.[Report_Date] AS Curr_Qtr_Date
, curr_qtr.[Sales] AS Curr_Qtr_Sales
, last_qtr.[Report_Date] AS Last_Qtr_Date
, last_qtr.[Sales] AS Last_Qtr_Sales
, curr_qtr.[Sales] - last_qtr.[Sales] AS Diff
, COALESCE((curr_qtr.[Sales] - last_qtr.[Sales]) / last_qtr.[Sales], 0) AS QoQ
FROM sub curr_qtr
LEFT JOIN sub last_qtr
ON curr_qtr.[Year] = last_qtr.[Year] -- ASSUMING FISCAL YEAR AND NOT CALENDAR YEAR
AND curr_qtr.[Quarter] = last_qtr.[Quarter] + 1
AND curr_qtr.[QuarterMonth] = last_qtr.[QuarterMonth]

Running Totals for the year

Trying to create running totals based on the year in my query as i'm showing the last 3 years of sales and commissions in my query and want running yearly totals for those for each salesperson listed
Tried various ways to get the data to do this but haven't been able to.
SELECT TOP (100) PERCENT 'abc' AS CompanyCode, abc.AR_Salesperson.SalespersonName, abc.AR_SalespersonCommission.SalespersonDivisionNo, abc.AR_SalespersonCommission.SalespersonNo,
SUM(abc.AR_SalespersonCommission.InvoiceTotal) AS InvoiceTotalSum, SUM(abc.AR_SalespersonCommission.CommissionAmt) AS CommissionAmtSum, DATENAME(month, abc.AR_SalespersonCommission.InvoiceDate)
AS Month, DATENAME(year, abc.AR_SalespersonCommission.InvoiceDate) AS Year, DATEPART(m, abc.AR_SalespersonCommission.InvoiceDate) AS MonthNumber
FROM abc.AR_Customer INNER JOIN
abc.AR_SalespersonCommission ON abc.AR_Customer.ARDivisionNo = abc.AR_SalespersonCommission.ARDivisionNo AND abc.AR_Customer.CustomerNo = abc.AR_SalespersonCommission.CustomerNo INNER JOIN
abc.AR_Salesperson ON abc.AR_SalespersonCommission.SalespersonDivisionNo = abc.AR_Salesperson.SalespersonDivisionNo AND
abc.AR_SalespersonCommission.SalespersonNo = abc.AR_Salesperson.SalespersonNo
GROUP BY abc.AR_Salesperson.SalespersonName, abc.AR_SalespersonCommission.SalespersonDivisionNo, abc.AR_SalespersonCommission.SalespersonNo, DATENAME(month, abc.AR_SalespersonCommission.InvoiceDate),
DATENAME(year, abc.AR_SalespersonCommission.InvoiceDate), DATEPART(m, abc.AR_SalespersonCommission.InvoiceDate)
HAVING (DATENAME(year, abc.AR_SalespersonCommission.InvoiceDate) > DATEADD(year, - 3, GETDATE()))
UNION
SELECT TOP (100) PERCENT 'XYZ' AS CompanyCode, xyz.AR_Salesperson.SalespersonName, xyz.AR_SalespersonCommission.SalespersonDivisionNo, xyz.AR_SalespersonCommission.SalespersonNo,
SUM(xyz.AR_SalespersonCommission.InvoiceTotal) AS InvoiceTotalSum, SUM(xyz.AR_SalespersonCommission.CommissionAmt) AS CommissionAmtSum, DATENAME(month, xyz.AR_SalespersonCommission.InvoiceDate)
AS Month, DATENAME(year, xyz.AR_SalespersonCommission.InvoiceDate) AS Year, DATEPART(m, xyz.AR_SalespersonCommission.InvoiceDate) AS MonthNumber
FROM xyz.AR_Customer INNER JOIN
xyz.AR_SalespersonCommission ON xyz.AR_Customer.ARDivisionNo = xyz.AR_SalespersonCommission.ARDivisionNo AND xyz.AR_Customer.CustomerNo = xyz.AR_SalespersonCommission.CustomerNo INNER JOIN
xyz.AR_Salesperson ON xyz.AR_SalespersonCommission.SalespersonDivisionNo = xyz.AR_Salesperson.SalespersonDivisionNo AND
xyz.AR_SalespersonCommission.SalespersonNo = xyz.AR_Salesperson.SalespersonNo
GROUP BY xyz.AR_Salesperson.SalespersonName, xyz.AR_SalespersonCommission.SalespersonDivisionNo, xyz.AR_SalespersonCommission.SalespersonNo, DATENAME(month, xyz.AR_SalespersonCommission.InvoiceDate),
DATENAME(year, xyz.AR_SalespersonCommission.InvoiceDate), DATEPART(m, xyz.AR_SalespersonCommission.InvoiceDate)
HAVING (DATENAME(year, xyz.AR_SalespersonCommission.InvoiceDate) > DATEADD(year, - 3, GETDATE()))
I expect the output to have running totals for the InvoiceTotalSum and CommissionAmt for each salesperson for the last 3 years. So of course January will be 0 for each person but Feb through December will have a running total
Sample data and desired results below. Desired results are the highlighted columns
Sample Data and Desired Results
2 things before I go to the solution.
First, I am not sure why you need an UNION into your query. I can see the difference between abc and xyz but it still looks strange.
It is surely possible your query can be shortened/simplified, which would need more info to tell.
Second, I do not see a valid reason why the running total should be 0 for January.
Explanation about that:
February (2nd month of the year): running total in your expected result contains the amount for 2 months
March: 3 months
April: 4 months
...
So January should contain the running total for 1 month (January itself).
Try the query below:
WITH MyData AS (
<Please paste your query here>
)
SELECT CompanyCode, SalesPersonName, SalesPersonDivisionNo, InvoiceTotalSum,
SUM(InvoiceTotalSum) OVER (PARTITION BY SalesPersonDivisionNo, SalesPersonNo, SalesPersonName, Year ORDER BY MonthNumber) AS InvoiceTotalRunningSum,
CommissionAmtSum,
SUM(CommissionAmtSum) OVER (PARTITION BY SalesPersonDivisionNo, SalesPersonNo, SalesPersonName, Year ORDER BY MonthNumber) AS CommissionAmtRunningSum,
Month, Year, MonthNumber
FROM MyData
ORDER BY CompanyCode, SalesPersonDivisionNo, SalesPersonNo, SalesPersonName, Year, MonthNumber
The magic takes place in the PARTION BY/ORDER BY
I think you need to review your query and simplify it.
a few notes :
if the CompanyCode is already existed within the database, join its table and link it with the current records instead of writing it manually.
DATENAME(year, ... ) the shorthand is YEAR()
DATEPART(m, ...) the shorthand is MONTH()
I encourage you to use aliases
(DATENAME(year, xyz.AR_SalespersonCommission.InvoiceDate) > DATEADD(year, - 3, GETDATE())) will exclude the first year and include the current.So, 2019-3 = 2016, yours will get 2017,2018, and 2019, while it should get 2016,2017, and 2018.
for your InvoiceTotalRunningSum use :
SUM(InvoiceTotalSum) OVER (PARTITION BY SalespersonNo ORDER BY MonthNumber UNBOUNDED PRECEDING)
this will do an accumulative sum on InvoiceTotalSum for each SalespersonNo. you can partition the records for each year, month ..etc. simply by adding more partitions, but I used your current query as sub-query, and did that instead :
read more about SELECT - OVER Clause (Transact-SQL)
try it out :
SELECT
'abc' AS CompanyCode
, SalespersonName
, SalespersonDivisionNo
, SalespersonNo
, InvoiceTotalSum
, SUM(InvoiceTotalSum) OVER (PARTITION BY SalespersonNo ORDER BY MonthNumber UNBOUNDED PRECEDING) InvoiceTotalRunningSum
, CommissionAmtSum
, SUM(CommissionAmtSum) OVER (PARTITION BY SalespersonNo ORDER BY MonthNumber UNBOUNDED PRECEDING) CommissionAmtRunningSum
, [Month]
, [Year]
, MonthNumber
FROM (
SELECT
'abc' AS CompanyCode
, ars.SalespersonName
, arsc.SalespersonDivisionNo
, arsc.SalespersonNo
, SUM(arsc.InvoiceTotal) InvoiceTotalSum
, SUM(arsc.CommissionAmt) CommissionAmtSum
, DATENAME(month, arsc.InvoiceDate) [Month]
, YEAR(arsc.InvoiceDate) [Year]
, MONTH(arsc.InvoiceDate) MonthNumber
FROM
abc.AR_Customer arc
INNER JOIN abc.AR_SalespersonCommission arsc ON arc.ARDivisionNo = arsc.ARDivisionNo AND arc.CustomerNo = arsc.CustomerNo
INNER JOIN abc.AR_Salesperson ars ON arsc.SalespersonDivisionNo = ars.SalespersonDivisionNo AND arsc.SalespersonNo = ars.SalespersonNo
GROUP BY
ars.SalespersonName
, arsc.SalespersonDivisionNo
, arsc.SalespersonNo
, YEAR(arsc.InvoiceDate)
, MONTH(arsc.InvoiceDate)
, DATENAME(month, arsc.InvoiceDate)
HAVING
YEAR(arsc.InvoiceDate) BETWEEN YEAR(GETDATE()) - 3 AND YEAR(GETDATE()) - 1 -- Only include the last three years (excluding current year)
) D

SQL Server: finding change between selected month and previous month's sales

I have the following table for example. I would like to calculate the changes increase or decrease from previous month. This will show a percentage of change from previous month.
Location Month Sales
A Jan 1753
B Jan 32130
C Jan 71353
D Jan 74885
E Jan 50241
F Jan 66393
A Feb 80633
B Feb 67918
C Feb 73330
D Feb 33269
E Feb 78915
F Feb 98817
A Mar 80633
B Mar 67918
C Mar 73330
D Mar 33269
E Mar 78915
F Mar 98817
I wan to create a table like following. I searched stack overflow but was not able to get table.
Location Selected Current_Month Prvisous_Month Change
A Feb 80633 1753 4500%
B Feb 67918 32130 111%
C Feb 73330 71353 3%
D Feb 33269 74885 -56%
E Feb 78915 50241 57%
F Feb 98817 66393 49%
If you can't change the datatype of the "Month" column, for whatever reason, then this solution may work
DECLARE #Table TABLE ([Location] CHAR(1), [Month] NVARCHAR(3), Sales INT )
INSERT INTO #Table
([Location], [Month], Sales)
VALUES
('A',N'Jan',1753),
('B',N'Jan',32130),
('C',N'Jan',71353),
('D',N'Jan',74885),
('E',N'Jan',50241),
('F',N'Jan',66393),
('A',N'Feb',80633),
('B',N'Feb',67918),
('C',N'Feb',73330),
('D',N'Feb',33269),
('E',N'Feb',78915),
('F',N'Feb',98817),
('A',N'Mar',80633),
('B',N'Mar',67918),
('C',N'Mar',73330),
('D',N'Mar',33269),
('E',N'Mar',78915),
('F',N'Mar',98817)
DECLARE #Selection NVARCHAR(3) = N'Feb' -- Enter Selected Month here
;WITH cteX
AS(
SELECT
T.[Location]
, T.[Month]
, MonthNum = MONTH([T].[Month] + ' 1 1900') --Use some dummy date here
, T.Sales
FROM #Table T
)
SELECT
T.[Location]
, Selected = T.Month
, CurrentMonth = T.Sales
, PreviousMonth = T1.Sales
, Change = CAST((T.Sales - T1.Sales) / (T1.Sales * 1.0) * 100.0 AS DECIMAL)
FROM cteX T
INNER JOIN
cteX T1 ON T1.MonthNum = T.MonthNum - 1
AND T1.[Location] = T.[Location]
WHERE
T.[Month] = #Selection
Output
Something like this should be a good start. As Cool_Br33ze noted, you should rethink the date column of this table.
SELECT
*,
referenceTimePeriod / NULLIF(comparisonTimePeriod, 0) -- avoid DIV0 errors
FROM (
SELECT Location, Sales
FROM myTable
WHERE month = 'jan'
) AS referenceTimePeriod
FULL JOIN(
SELECT Location, Sales
FROM myTable
WHERE month = 'feb'
) AS comparisonTimePeriod ON referenceTimePeriod.Location = comparisonTimePeriod .Location
SELECT A.Location, 'Feb' AS Selected, A.Sales AS Current_Month
, B.Sales AS Prvisous_Month, (A.Sales - B.Sales)/ B.Sales AS Change
FROM YourTable A JOIN YourTable B
ON A.Month = B.Month + 1 -- You will have to represent Months by numbers
WHERE A.Month = 2 -- Selected month
Assuming that you change the Month attribute to date then you can use a LAG window function easily like this
SELECT location,
month,
sales,
lag(sales) over (order by month) previous,
(sales/lag(sales) over (order by month) - 1) * 100 as change
FROM your_table
WHERE month = 'feb'
The major issue now in your task is the correct ordering of Month which would be much more easier with date, or numbers.
EDIT: You can use the ordering solution of Cool_Br33ze for current data:
SELECT location,
month,
sales,
lag(sales) over (order by MONTH([T].[Month] + ' 1 1900')) previous, -- taken from Cool_Br33ze solution
(sales/lag(sales) over (order by MONTH([T].[Month] + ' 1 1900')) - 1) * 100 as change
FROM your_table
WHERE month = 'feb'
However, the best option is to change the data type of Month ...