How to get quarterly data from monthly in SQL Server - sql

I have table where I am having monthly data like below.
Here my AvgSpeedOfAnswer column is calculated like this:
avg(SpeedOfAnswer)
Table:
Date
AvgSpeedOfAnswerMonth
7/1/2022
20.8
8/1/2022
22.6
9/1/2022
24.9
Now my requirement is I need to create a query where I can get quarterly data from above monthly table data.
I wrote a query like this:
SELECT
'Quarterly' AS TrendType,
DATEADD(Q, DATEDIFF(Q, 0, TrendStartdate), 0) AS TrendStartdate,
SUM(AvgSpeedOfAnswer)
FROM
Month_Stats
GROUP BY
DATEADD(Q, DATEDIFF(Q, 0, TrendStartdate), 0)
ORDER BY
DATEADD(Q, DATEDIFF(Q, 0, TrendStartdate), 0)
I am not sure what should I need to take for AvgSpeedOfAnswer.
Is it SUM(AvgSpeedOfAnswerMonth) or AVG(AvgSpeedOfAnswerMonth) or AVG(SUM(AvgSpeedOfAnswerMonth))?
Could anyone please suggest?

As others mentioned.
You need to use DATEPART
SELECT
'Quarterly' AS TrendType,
DATEFROMPARTS(YEAR(Date), ((DATEPART(Q, Date) - 1) * 3) + 1, 1) AS TrendStartdate,
AVG(AvgSpeedOfAnswerMonth) AS AvgSpeedOfAnswerQuarter
FROM
Month_Stats
GROUP BY
YEAR(Date),
DATEPART(Q, Date)
ORDER BY
YEAR(Date),
DATEPART(Q, Date)

you can use DATEPART and QUARTER
CREATE TABLE tabl11
([Date] datetime, [AvgSpeedOfAnswerMonth] DECIMAL(10,1))
;
INSERT INTO tabl11
([Date], [AvgSpeedOfAnswerMonth])
VALUES
('2022-07-01 02:00:00', 20.8),
('2022-08-01 02:00:00', 22.6),
('2022-09-01 02:00:00', 24.9)
;
3 rows affected
SELECT YEAR([Date]), DATEPART(QUARTER, [Date]), SUM([AvgSpeedOfAnswerMonth]) sum_quarterly FROM tabl11
GROUP BY YEAR([Date]),DATEPART(QUARTER, [Date])
(No column name)
(No column name)
sum_quarterly
2022
3
68.3
fiddle

I think you need avg (AvgSpeedOfAnswerMonth) to get the quarterly average speed over the quarter. Sum(AvgSpeedOfAnswerMonth) and avg(sum(AvgSpeedOfAnswerMonth) give the same value, which is the sum of the quarterly values.

Use the DATEPART function with parameter QUARTER, like
select 'Quarterly' as Quarterly, date as date from yourTable
group by DATEPART(quarter, date)
order by DATEPART(quarter, date)

Related

Add week number column in query results from existing date column

The current query is shown below and I am struggling with trying to add a column to my results query, where it converts the PRODUCTION_DATE into fiscal week.
SELECT
ORDER_QTY, SKU, INVOICE_NUMBER, CUSTOMER_NUMBER, ROUTE,
ALLOCATED_QTY, SHORTED_QTY, PRODUCTION_DATE
FROM
[DATEBASE_NAME].[XYZ].[ORDERS]
WHERE
[PRODUCTION_DATE] >= DATEADD(day, -300, GETDATE())
AND [PRODUCTION_DATE] <= GETDATE()
I believe DATEPART is part of the function, I just don't know how to execute. End goal would be a column in the results that just returns the fiscal week along with all other data. The little query above returns my data proper now, I am just trying to get that column in.
Thanks for looking.
As you have already mentioned about DATEPART;
(And you were almost there !!)
Here is the modified query
SELECT
ORDER_QTY, SKU, INVOICE_NUMBER, CUSTOMER_NUMBER, ROUTE,
ALLOCATED_QTY, SHORTED_QTY, PRODUCTION_DATE,
DATEPART(wk, PRODUCTION_DATE) AS FISCAL_WEEK
FROM
[DATEBASE_NAME].[XYZ].[ORDERS]
WHERE
[PRODUCTION_DATE] >= DATEADD(day, -300, GETDATE())
AND [PRODUCTION_DATE] <= GETDATE();

How to select data's from this today,week and month sperately?

I have a problem that is I am unable to resolve as of now.
I need to get the data of
this day, this week and this month
I have a table reminder where I want to select reminders according to
following parameters.
1. Today
2. This Week
3. This Month
The column rdate having the date format in dd-mm-yyyy which is stored as nvarchar
For example
If I execute this weeks query I should get data starting from this week i.e.
If it is Friday I should get data from starting from Sunday to Saturday of that week
How can I get the data as mentioned above. I have searched a lot on internet but I didn't get the solution?
This is the query I have been trying
SELECT
*
FROM
reminder
WHERE
date > DATE_SUB(GETDATE(), INTERVAL 1 DAY)
ORDER BY
rdate DESC;
Where I'm converting nvarchar to date format.
If it's not possible to change the [date] column's data type to DATE, then you will incur a massive performance penalty when trying to filter by date.
Add computed column to table
We can add a computed column that will store the date in the correct format, and then index it for quick searchiing:
ALTER TABLE reminder
ADD Date_Value AS (CONVERT(DATE, '12-05-2016', 105)) PERSISTED;
-- This should yield superior performance
CREATE NONCLUSTERED INDEX IX_Date_Value ON reminder (Date_Value);
Table-valued function to calculate date range
Now, let's create an inline table-valued function to generate the date range for specific period types:
CREATE FUNCTION [dbo].[tvfn_Get_Date_Range](
#Period_Type VARCHAR(100)
)
RETURNS
TABLE
AS RETURN
(
WITH date_range AS(
SELECT CAST(GETDATE() AS DATE) d
-- This line works correctly if your week starts on Sunday
,CAST(DATEADD(WEEK, DATEDIFF(WEEK, '19050101', GETDATE()), '19050101') AS DATE) AS week_start
,CAST(DATEADD(DAY, - DAY(GETDATE()) + 1, GETDATE()) AS DATE) AS month_start
,CAST(DATEADD(MONTH, 1, DATEADD(DAY, - DAY(GETDATE()), GETDATE())) AS DATE) AS month_end
)
SELECT d AS From_Date
,d AS To_Date
FROM date_range
WHERE #Period_Type = 'DAY'
UNION ALL
SELECT week_start
,DATEADD(DAY, 7, week_start)
FROM date_range
WHERE #Period_Type = 'WEEK'
UNION ALL
SELECT month_start
,month_end
FROM date_range
WHERE #Period_Type = 'MONTH'
)
In the above function, week starts on Sunday. If you need this to be configurable, then take a look at the answer to SET DATEFIRST in FUNCTION.
Fast, simple querying now possible
You can now use the two together using a simple query:
SET #Range VARCHAR(100) = 'WEEK'
SELECT *
FROM reminder
CROSS APPLY [dbo].[tvfn_Get_Date_Range](#Range) dr
WHERE Date_Value BETWEEN dr.Date_From AND dr.Date_To
If you can't change the columns data type to Date (or DateTime), you must convert it to date in the query.
Here is one way to get the data for today, this week and this month:
Get records from today:
SELECT *
FROM reminder
WHERE CONVERT(Date, [date], 105) = CAST(GETDATE() as date)
ORDER BY rdate DESC;
Get records from this week:
SELECT *
FROM reminder
WHERE DATEPART(WEEK, CONVERT(Date, [date], 105)) = DATEPART(WEEK, GETDATE())
AND DATEPART(YEAR, CONVERT(Date, [date], 105)) = DATEPART(YEAR, GETDATE())
ORDER BY rdate DESC;
Get records from this Month:
SELECT *
FROM reminder
WHERE DATEPART(MONTH, CONVERT(Date, [date], 105)) = DATEPART(MONTH, GETDATE())
AND DATEPART(YEAR, CONVERT(Date, [date], 105)) = DATEPART(YEAR, GETDATE())
ORDER BY rdate DESC;
To my knowledge, SQL server internally deals with date format as MM/dd/yyyy.
Usually I prefer to save date as string in SQL table since it's easier for inserting and retrieving.
For example, suppose that the column rdate is defined as follows in your table reminder:
[rdate] nvarchar NULL
Then you can customize the select statement for a week as follows:
"Select R.* From reminder R Where CAST(R.rdate as datetime) between
'03/04/2011' AND '03/11/2011'"
And for 10 days as follows:
"Select R.* From reminder R Where CAST(R.rdate as datetime) between
'03/04/2011' AND '03/14/2011'"
And so on. If this is not what you want, please provide more details about your requirements.

Taking sum of column based on date range in T-Sql

I have a column called Work Done where on daily basis some amount of work is caarried out. It has columns
Id, VoucherDt, Amount
Now my report has scenario to print the sum of amount till date of the month. For example if Current date is 3rd September 2013 then the query will pick all records of 1st,2nd and 3rd Sept and return a sum of that.
I am able to get the first date of the current month. and I am using the following condition
VoucherDt between FirstDate and GetDate() but it doesnot givign the desired result. So kindly suggest me the proper where condition.
SELECT SUM(AMOUNT) SUM_AMOUNT FROM <table>
WHERE VoucherDt >= DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0)
AND VoucherDt < DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 1)
I think that there might be a better solution but this should work:
where YEAR(VoucherDt) = YEAR(CURRENT_TIMESTAMP)
and MONTH(VoucherDt) = MONTH(CURRENT_TIMESTAMP)
and DAY(VoucherDt) <= DAY(CURRENT_TIMESTAMP)
Try to calc the number of months from the first date that you can store in a datetime an your target dates.
SELECT SUM(amount)
FROM
(
SELECT 100000 AS amount, '2013-09-03' AS dt
UNION ALL SELECT 10000, '2013-09-02'
UNION ALL SELECT 1000, '2013-09-01'
UNION ALL SELECT 100, '2013-08-02'
UNION ALL SELECT 10, '2013-01-31'
UNION ALL SELECT 2, '2012-09-03'
UNION ALL SELECT 2, '2012-09-02'
UNION ALL SELECT 1, '2012-09-01'
) SourceData
WHERE DATEDIFF(m, '1900-1-1', GETDATE()) = DATEDIFF(m, '1900-1-1', SourceData.dt)

SQL get Monthly, and weekly data

I am writing a query to give me number of products sold this week, this month and this year (3 separate columns) on a week to date, month to date and year to date scale meaning today for example it will show products sold since monday, since the first of the month and since first of the year and this is to continue with each following week, month and year as time goes, there also are to be 3 other columns with the same logic for last year. What i need is help getting the date query using DATEADD or DATEDIFF (example (DATEADD(minute, -15, GETDATE())).
thank you very much and also i'm using SQL Server 2008
Here is some untested code which could probably be optimized, but should get you going in the right direction. This uses a PIVOT operation to transform your rows into columns.
SELECT WeekCount, MonthCount, YearCount
FROM
(
SELECT ProductId,
CASE
WHEN ProductSoldDate >= DATEADD(dd, 1 - DATEPART(dw, GETDATE()), GETDATE())
THEN 'WeekCount'
WHEN ProductSoldDate >= DATEADD(mm, DATEDIFF(mm,0,GETDATE()), 0)
THEN 'MonthCount'
WHEN ProductSoldDate >= DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0)
THEN 'YearCount'
END as lbl
FROM Products
) ProductSales
PIVOT
(
COUNT(ProductId)
FOR lbl IN ([WeekCount], [MonthCount], [YearCount])
) t
Here is the SQL Fiddle.
Good luck.
Using the DATEADD function
In some circumstances, you might want to add an interval of time to a DATETIME or SMALLDATETIME value or subtract an interval of time. For example, you might need to add or subtract a month from a specific date. You can use the DATEADD function to perform this calculation. The function takes the following syntax:
DATEADD(date/time_part, number, date)
Example:
SELECT OrderDate, DATEADD(mm, 3, OrderDate) AS NewDate
FROM Sales.Orders
WHERE OrderID = 1001
Using the DATEDIFF function
The DATEDIFF function calculates the time interval between two dates and returns an integer that represents the interval. The function takes the following syntax:
DATEDIFF(date/time_part, start_date, end_date)
Example:
SELECT OrderDate, DelivDate,
DATEDIFF(hh, OrderDate, DelivDate) AS HoursDiff
FROM Sales.Orders
WHERE OrderID = 1002

sql get count of month

In SQLExpress, I have a table that contains a datetime-column. It is formatted like this:
19.03.2012 00:00:00
Now, there are a lot of dates in there and I want to build a WPFChart, that shows me, how much dates are in march, in april and so on.
How can I manage this in sql that I get the count of one month?
Use:
select month(dateColumn), count(*)
from table
group by month(dateColumn)
You can extract the month of a date with Month() funciton.
than with a simple group by, you get the count for every month
To get only one month...
SELECT
COUNT(*),
SUM(valueColumn)
FROM
yourTable
WHERE
dateColumn >= '20120101'
AND dateColumn < '20120201'
To get multiple months, but grouped by month (and accounting for year).
SELECT
DATEADD(MONTH, DATEDIFF(MONTH, 0, dateColumn), 0),
COUNT(*),
SUM(valueColumn)
FROM
yourTable
WHERE
dateColumn >= '20110301'
AND dateColumn < '20120301'
GROUP BY
DATEADD(MONTH, DATEDIFF(MONTH, 0, dateColumn), 0)