Group by Weeks for successive years - sql

I am trying to aggregate data by weeks. My sample query looks like
SET DATEFIRST 1
Select ID,
DATENAME(week, p.SellingDate) as SellingWeek,
DATENAME(year, p.SellingDate) as SellingYear,
SUM(Quantity),
SUM(Revenue)
From dbo.Sales
Where
p.SellingDate >=’2015-12-20’ and P.SellingDate < ’2016-02-27’
Group by ID,
DATENAME(week, p.SellingDate),
DATENAME(year, p.SellingDate)
When I try to do this, I am facing an issue:
The query returns correct data but the issue appears in the last week of 2015. It considers only the days (12/28 to 12/31) that are part of 2015 as the 53rd week and it considers the remaining part (01/01 to 01/03) as a new week of 2016. I only one row that has data for the whole week i.e. 12/28 to 01/03) but SQL Server returns 2 rows. Is there a workaround this?

I would think you want to create a construct for grouping on week start and week end, then using that to group by for your aggregation clauses.
SET DATEFIRST 1
Select DATEADD(dd, -(DATEPART(dw, p.SellingDate)-1), p.SellingDate) AS [WeekStart],
DATEADD(dd, 7-(DATEPART(dw, p.SellingDate)), p.SellingDate) AS [WeekEnd],
SUM(Quantity),
SUM(Revenue)
From dbo.Sales
Where
p.SellingDate >= '2015-12-20' and P.SellingDate < '2016-02-27'
Group by ID,
DATEADD(dd, -(DATEPART(dw, p.SellingDate)-1), p.SellingDate),
DATEADD(dd, 7-(DATEPART(dw, p.SellingDate)), p.SellingDate)

You can fix this by setting the week not based on the date of the sale but rather on the monday of week of the date of the sale.
select
getdate() as today
datename(week, dateadd(dd,-1* (datepart(weekday, getdate())-1),getdate())) as monday,

Related

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

Getting the previous months data

This seems to have been answered several times for the past 30 days. But seemingly not what I need.
If, for example, today is July 10th, 2012. I'm looking to pull all of June's data. I will need to run this query several days after the start of each month
There is certainly better ways to do this, but one way would be this:
DECLARE #Date DATETIME
SET #Date = '20120710'
SELECT *
FROM YourTable
WHERE YourDateColumn >= CONVERT(VARCHAR(6),DATEADD(MONTH,-1,#Date),112)+'01'
AND YourDateColumn < CONVERT(VARCHAR(6),#Date,112)+'01')
-- first day of previous month
select DateAdd(Month, DateDiff(Month, 0, GetDate())-1,0)
-- last day of previous month
Select DateAdd(day,-1,DateAdd(Month,1,DateAdd(Month,
DateDiff(Month, 0,GETDATE())-1,0)))
Please replace GETDATE() with your date column
Ah, in that case you need something like:
SELECT *
FROM
reporting_table_name_goes_here
WHERE
DATEPART(month, YourDateColumn) = DATEPART(month, DATEADD(month, -1, getdate()))
AND DATEPART(year, YourDateColumn) = DATEPART(year, DATEADD(month, -1, getdate()))
Check out MSDN for details.

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)

Compare Monday's data to previous Mondays in SQL Server

I am trying to figure out how to compare the current day's data to the same data from a week ago, 2 weeks, etc. Let's say I have a table called "Order" with 2 columns:
Order table
-----------
OrderID int identity
OrderDate datetime
If today, is Monday, I would like to be able to compare the number of orders from today to the previous Mondays for an entire year. Is this possible with a single SQL Server query? I'm using SQL 2008 if it makes a difference.
select CAST (OrderDate as date) as [Date], COUNT(*)
from Orders
where OrderDate > DATEADD(YEAR,-1, getdate())
and DATEPART(DW,OrderDate ) = DATEPART(DW,GETDATE())
group by CAST (OrderDate as date)
Try
SELECT [ColumnsYouWant]
FROM [OrderTable]
WHERE datepart(weekday, OrderDate) = datepart(weekday, getdate())
AND OrderDate >= dateadd(yyyy, -1, getdate())
This gives you Monday order counts by week number:
select year(OrderDate) as Year,
DATEPART(WEEK, OrderDate) as Week,
COUNT(*) as MondayOrderCount
from Order
where DATEPART(WEEKDAY, OrderDate) = 2
group by year(OrderDate), DATEPART(WEEK, OrderDate)
order by Year, Week

How can I count and group by between two date?

For example,
the start date = '20100530' and
the end date = '20100602'
How can I write a SQL to display the below result?
month: may, 2 days
month: June, 2 days
Use a recursive CTE to generate all of the dates between the start and end, and then do a simple group and count (caution, not tested, but should be close if not exactly right):
with dates (the_date) as (
select #start_date
UNION ALL
select dateadd(dd, 1, the_date) from dates where the_date <= #end_date
)
select
datepart(mm, the_date) month,
count(*) num_days
from
dates
group by
datepart(mm, the_date)
TBH, you really need to provide more schema and information about the source data. However, given what little we know, you should be able to write:
Select DateName('month', [Date]) As Month
, Cast(DateDiff(d, #StartDate, #EndDate) As varchar(10) - 1) + ' days'
From Table
Where [Date] Between #StartDate And #EndDate
What we'd need to know to refine our solutions is exactly how 2 days is supposed to be calculated. Is it the days between the start and end date? Is it the day of the second parameter?