filmov
tv
📊 How to Compare Quarters in SQL Server (Quarterly Sales Figures, etc.)
Показать описание
Here's a relatively straightforward way to compare quarters in SQL Server's T-SQL using GROUP BY, LAG, OVER and PARTITION BY. As such it's a great way to compare sales data across quarters, although it can also be used with other numerical data.
00:00 - Introduction
00:27 - Grouping by Quarters
01:39 - Basic Quarterly Comparison
03:23 - Quarterly Comparison Spanning Years
If you're new to sales and marketing then you need to know that the year is divided into 4 quarterly periods. Q1 is January - March (inclusive), Q2 is April - June, Q3 is July - September and Q4 is October - December. Also bear in mind that these may be different to a company's financial reporting year. Many companies like to end their financial years at the end of their juristiction's tax year for example.
Here's a query that will group the Northwind sales data by quarter, including carrying over the previous year's Q4's sales figures into Q1 of the following year:
SELECT COUNT(OrderID) AS 'NumberOfOrders', YEAR(OrderDate) AS 'Year',
DATEPART(qq, OrderDate) AS 'Quarter',
LAG(COUNT(OrderID)) OVER (ORDER BY CONCAT(YEAR(OrderDate), 'Q', DATEPART(qq, OrderDate)))
AS 'Previous Quarter'
FROM Orders
GROUP BY YEAR(OrderDate), DATEPART(qq, OrderDate)
ORDER BY YEAR(OrderDate) DESC, DATEPART(qq, OrderDate) DESC
If you found this video leave a LIKE and SUBSCRIBE for more coding videos.
00:00 - Introduction
00:27 - Grouping by Quarters
01:39 - Basic Quarterly Comparison
03:23 - Quarterly Comparison Spanning Years
If you're new to sales and marketing then you need to know that the year is divided into 4 quarterly periods. Q1 is January - March (inclusive), Q2 is April - June, Q3 is July - September and Q4 is October - December. Also bear in mind that these may be different to a company's financial reporting year. Many companies like to end their financial years at the end of their juristiction's tax year for example.
Here's a query that will group the Northwind sales data by quarter, including carrying over the previous year's Q4's sales figures into Q1 of the following year:
SELECT COUNT(OrderID) AS 'NumberOfOrders', YEAR(OrderDate) AS 'Year',
DATEPART(qq, OrderDate) AS 'Quarter',
LAG(COUNT(OrderID)) OVER (ORDER BY CONCAT(YEAR(OrderDate), 'Q', DATEPART(qq, OrderDate)))
AS 'Previous Quarter'
FROM Orders
GROUP BY YEAR(OrderDate), DATEPART(qq, OrderDate)
ORDER BY YEAR(OrderDate) DESC, DATEPART(qq, OrderDate) DESC
If you found this video leave a LIKE and SUBSCRIBE for more coding videos.