Does SQL automatically calculate month to month start and end dates? - sql

I am trying to get total amount of sales sold in 1 month. For example, from 4/1/15 - 4/30/15.
I am getting a span of 3/30/15 - 4/30/15.
Here is my SQL:
SELECT Customer.custno
, Customer.enteredDate AS 'Date Entered'
, COUNT(BasicPolInfo.polid) AS 'Number of Policies'
, SUM(COUNT(BasicPolInfo.polid)) OVER (ORDER BY Customer.custno ROWS
BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS TotalAmount
FROM Customer
INNER JOIN BasicPolInfo ON Customer.custid = BasicPolInfo.custid
WHERE BasicPolInfo.polid IS NOT NULL
AND Customer.firstname IS NOT NULL
AND Customer.enteredDate BETWEEN DATEADD(MONTH, -1, GETDATE()) AND
DATEADD(MONTH, 0, GETDATE())
GROUP BY Customer.custno
, Customer.firstname
, Customer.lastname
, Customer.entereddate
ORDER BY Customer.enteredDate ASC
The results I am getting are from the dates 2015-04-30 to 2015-03-30. I am trying to get 2015-04-30 to 2015-04-01.
And for the next month to also be from 2015-05-31 to 2015-05-01
Any help would be appreciated! Thank you!

Since you are on 2012 you can use EOMONTH()
WHERE Customer.enteredDate >= DATEADD(DAY, 1, EOMONTH(GETDATE(), -1))
AND < DATEADD(DAY, 1, EOMONTH(GETDATE()))
or you could match the month and year only.
where month(Customer.enteredDate) = month(getDate())
and year(Customer.enteredDate) = year(getDate())

Customer.enteredDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, current_timestamp), 0)
AND Customer.enteredDate < DATEADD(MONTH, DATEDIFF(MONTH, 0, current_timestamp) + 1, 0)

Related

Get total sales of last 12 months even if values are null

I have following code in which it presently gives month wise Total Sales for current year, I need to get total sales from last month of previous year to current month of this year.
My query is as follows:
;WITH mcte AS (
SELECT DATEADD(year, -1, getdate()) as MONTH_NAME
UNION ALL
SELECT DATEADD(MONTH,1,MONTH_NAME)
FROM mcte
WHERE DATEPART(MONTH,MONTH_NAME) < 12),octe AS(
SELECT (DATENAME (MONTH, DATEADD ( MONTH, DATEPART(MONTH, OI.CreatedDate), -1) )) AS MONTH_NAME,
SUM (OI.ItemQty * OI.TotalPrice) AS TOTAL_SALES
FROM Order_Item OI
GROUP BY MONTH(OI.CreatedDate))
SELECT DATENAME(MONTH,m.MONTH_NAME) + '' + DATENAME(YEAR,m.MONTH_NAME) as
MONTH_NAME, o.TOTAL_SALES FROM mcte m LEFT JOIN octe o ON o.MONTH_NAME = DATENAME(MONTH,m.MONTH_NAME)
and I am getting records
MONTH_NAME TOTAL_SALES
July2019 54023.45
August2019 NULL
December2019 NULL
September2019 NULL
October2019 NULL
November2019 NULL
Here I am only getting data for previous year only, not getting data for current year.Can anyone please guide me on this.
Thank you
You are only generating months up to 12. Try replacing the first CTE with:
WITH mcte AS (
SELECT DATEADD(year, -1, getdate()) as MONTH_NAME
UNION ALL
SELECT DATEADD(MONTH,1,MONTH_NAME)
FROM mcte
WHERE month_name < GETDATE()
),
Note the difference is the WHERE clause.
The entire query should look like this:
WITH months AS (
SELECT DATEFROMPARTS(YEAR(getdate()) - 1, MONTH(getdate()), 1) as month
UNION ALL
SELECT DATEADD(MONTH, 1, month)
FROM months
WHERE EOMONTH(month) < GETDATE()
)
SELECT m.month, SUM(OI.ItemQty * OI.TotalPrice) AS TOTAL_SALES
FROM months m LEFT JOIN
Order_Item OI oi
ON oi.CreatedDate >= m.month AND
oi.CreatedDate < DATEAADD(month, 1, m.month)
GROUP BY m.month
Try doing this:
DECLARE #CurDate DATE = GET_DATE()
DECLARE #OneYearPrior DATE = DATEADD(YEAR, -1, #CurDate)
WITH relevant_months(start_date, month_of_sale, year_of_sale) AS (
SELECT
#CurDate AS start_date,
MONTH(#CurDate) as month_of_sale,
YEAR(#CurDate) as year_of_sale
UNION ALL
SELECT DATEADD(MONTH, -1, start_date) AS start_date,
MONTH(DATEADD(MONTH, -1, start_date)) as month_of_sale,
YEAR(DATEADD(MONTH, -1, start_date)) AS year_of_sale
FROM relevant_months
WHERE DATEADD(MONTH, -1, start_date) >= #OneYearPrior
),
relevant_data AS (
SELECT OI.CreatedDate,
OI.ItemQty,
OI.TotalPrice,
MONTH(OI.CreatedDate), AS month_of_sale,
YEAR(OI.CreatedDate) AS year_of_sale
FROM Order_Item OI
WHERE OI.CreatedDate >= DATEADD(YEAR, -1, GETDATE())
)
SELECT rm.month_of_sale as month, rm.year_of_sale as year,
SUM(rd.ItemQty*rd.TotalPrice) as total_sales
FROM relevant_months rm
LEFT JOIN relevant_data rd
ON rm.month_of_sale = rd.month_of_sale
AND rm.year_of_sale = rd.year_of_sale
GROUP BY rm.month_of_sale, rm.year_of_sale
ORDER BY rm.year_of_sale asc, rm.month_of_sale asc

Get records of last 2 months (current year), and last month(last year)

I need to get records of last 2 months and last month(last year) based on my table field paidDate, using SQL server 2016.
Suppose, I run the query on Feb 1st/2nd, 2020. I need the monthly data from December 2019, January 2020, as well as January 2019.
What's the SQL query for this? Is it possible to club all of these scenario into one?
Then for the previous 2 months the paidDate would be :
A) Higher or equal than the first day of 2 months ago
B) Lower than the first day of the current month.
Similar for the month of a year ago.
So try something like this:
SELECT *
FROM YourTable
WHERE
(
paidDate >= DATEADD(month, -2, DATEADD(month, DATEDIFF(month, 0, GetDate()), 0))
AND paidDate < DATEADD(month, DATEDIFF(month, 0, GetDate()), 0)
)
OR
(
paidDate >= DATEADD(month, -13, DATEADD(month, DATEDIFF(month, 0, GetDate()), 0))
AND paidDate < DATEADD(year, -1, DATEADD(month, DATEDIFF(month, 0, GetDate()), 0))
)
LukStorm has the better answer in terms of performance (and I've upvoted it). But if you want complete months and don't care about indexing, then I would suggest datediff():
where datediff(month, paiddate, getdate()) in (1, 2, 13)
This gets the complete months that are 1 month, 2 months, and 13 months in the past.
You can try the logic as below-
SELECT *
FROM your_table
WHERE
(
YEAR(paidDate) = YEAR(DATEADD(MM,-1, getdate()))
AND
MONTH(paidDate) = MONTH(DATEADD(MM,-1, getdate()))
)
OR
(
YEAR(paidDate) = YEAR(DATEADD(MM,-2, getdate()))
AND
MONTH(paidDate) = MONTH(DATEADD(MM,-2, getdate()))
)
OR
(
YEAR(paidDate) = YEAR(DATEADD(MM,-13, getdate()))
AND
MONTH(paidDate) = MONTH(DATEADD(MM,-13, getdate()))
)

Can anyone check query I want to extract years and month columns too

Want to extract data month wise for last 2 years. Below query actually calculating 1 month data.
SELECT CAST (g1.no_of_member_cancelled AS DECIMAL(10, 2)) /
CAST (g2.no_of_live_member AS DECIMAL(10, 2)) AS x,
g1.homebranch,
g1.locationname
FROM (SELECT Count(*) AS No_of_Member_Cancelled,
M.homebranch,
M.locationname
FROM ax.memberships M
WHERE M.activeend BETWEEN Dateadd(month, Datediff(month, 0, Getdate())
- 1, 0)
AND
Dateadd(month, Datediff(month, 0,
Getdate())
, -1)
GROUP BY M.homebranch,
M.locationname) AS g1
INNER JOIN (SELECT Count(*)AS No_of_Live_Member,
M.homebranch,
M.locationname
FROM ax.memberships M
WHERE M.activestart BETWEEN Dateadd(month, Datediff(month, 0
,
Getdate()) - 1,
0) AND
Dateadd(month, Datediff(month,
0, Getdate(
)), -1)
GROUP BY M.homebranch,
M.locationname
) AS g2
ON g1.homebranch = g2.homebranch
AND g1.locationname = g2.locationname
Want to extract data month wise for last 2 years. Below query actually calculating 1 month data.

SQL: Selecting current month last year

I currently select data from the current month LAST year. This works fine with
SELECT cast(CREATED as date) AS DATE, COUNT([ID]) AS BOOKINGS, SUM([TOTCOST]) AS Sales
from BOOKING
WHERE
CREATED >= DATEADD(month, datediff(month, 0, getdate())-12, 0)
AND
CREATED < DATEADD(month, datediff(month, 0, getdate())-11, 0)
GROUP BY cast(CREATED as date)
ORDER BY cast(CREATED as date)
However, rather than return 1st to 31st July, I would like to return 2nd July 2014 to 1st August 2014 inclusive. So effectivly +1 day on that current month.
Is this possible?
Yes, simply add 1 to the result of your calculation.
SELECT cast(CREATED as date) AS DATE, COUNT([ID]) AS BOOKINGS, SUM([TOTCOST]) AS Sales
from BOOKING
WHERE
CREATED >= (DATEADD(month, datediff(month, 0, getdate())-12, 0) + 1)
AND
CREATED < (DATEADD(month, datediff(month, 0, getdate())-11, 0) + 1)
GROUP BY cast(CREATED as date)
ORDER BY cast(CREATED as date)

Grouping by day from 2 tables

I have 2 tables: "orders" and "visits". in the orders table i'm saving some details about the order including "userIP" and "orderDate". in the visits table i'm saving details everytime a user visiting my web page including "userIP" and "visitDate". i'm using ASP.NET and SQL SERVER 2005.
i want to create a statistic table whitin i save the number of users visited and the number of users that ordered BOTH GROUPED BY DAY so far i got:
select count(userIP) as NumOfOrders,
dateadd(dd, datediff(dd, 0, orderDate),0) as Date
from Orders
group by dateadd(dd, datediff(dd, 0, orderDate), 0)
this works fine and give me the number of orders grouped by day,
but how do i add the total visits grouped by day to this?
I would do this:
SELECT v.userIP, NumOfVisits, NumOfOrders, v.Date
FROM (
SELECT userIP, count(*) as NumOfVisits,
dateadd(dd, datediff(dd, 0, visitDate),0) as Date
FROM visits
GROUP BY userIP, dateadd(dd, datediff(dd, 0, orderDate), 0)) v
LEFT JOIN (
SELECT userIp, count(*) as NumOfOrders,
dateadd(dd, datediff(dd, 0, orderDate),0) as Date
FROM orders
GROUP BY UserIP, dateadd(dd, datediff(dd, 0, orderDate), 0)) o
ON o.UserIP = v.UserIP
AND o.Date = v.Date
and your result should be like:
78.34.5.11 | 3 | 1 | 2009.10.06
78.34.5.19 | 9 | 0 | 2009.10.06
if you don't need to group by userIP, you can do this:
SELECT NumOfVisits, NumOfOrders, v.Date
FROM (
SELECT count(*) as NumOfVisits,
dateadd(dd, datediff(dd, 0, visitDate),0) as Date
FROM visits
GROUP BY dateadd(dd, datediff(dd, 0, visitDate), 0)) v
LEFT JOIN (
SELECT count(*) as NumOfOrders,
dateadd(dd, datediff(dd, 0, orderDate),0) as Date
FROM orders
GROUP BY dateadd(dd, datediff(dd, 0, orderDate), 0)) o
ON o.Date = v.Date
and your result will look like:
12 | 1 | 2009.10.06
SELECT COALESCE(O1.Date, V1.Date) Date,
COALESCE(O1.NumOfOrders, 0) NumOfOrders,
COALESCE(V1.TotalVisits, 0) TotalVisits
FROM
(select dateadd(dd,0, datediff(dd, 0, O.orderDate)) Date,
count(O.userIP) NumOfOrders
from Orders O
group by dateadd(dd,0, datediff(dd, 0, O.orderDate))) O1
FULL JOIN
(select dateadd(dd,0, datediff(dd, 0, V.visitDate)) Date,
count(V.userIP) TotalVisits
from Visits V
group by dateadd(dd,0, datediff(dd, 0, V.visitDate))) V1
on O1.Date = V1.Date