Group dates by week? - sql

I'm trying to group a series of dates by week. So far I have the following:
SELECT DATEPART(week, CONVERT(VARCHAR(50), e.event_date, 107)) AS 'Date' ,
c.setting_secondary AS 'Workflow Cat' ,
d.setting_main AS 'Error Type' ,
SUM(e.event_count) AS 'Total'
FROM marlin.support_events AS e
INNER JOIN marlin.support_config AS c
ON e.event_category = c.setting_code
AND config_code = 60
INNER JOIN marlin.support_config AS d
ON e.event_type = d.setting_code
AND d.config_code = 70
WHERE e.event_date BETWEEN DATEADD(MONTH, -2, GETDATE()) AND GETDATE()
AND c.setting_secondary = 'Expenditure Voucher'
AND d.setting_main IN ( 'Unstarted' , 'Timeout' )
GROUP BY
DATEPART(week, CONVERT(VARCHAR(50), e.event_date, 107)) ,
c.setting_secondary ,
d.setting_main ,
e.event_summary
This shows me the week number but not the date that week started within, like so:
How can I show what date this week begins with?
Answer:
Answer identified below and an alternate method I also found for doing this:
DATEADD(dd, -(DATEPART(dw, e.event_date)-1), e.event_date)

You can get the year part from the date, append the first day of first month and then add the (#week - 1) to get the starting day of the week the event_date belongs to, as follows:
SELECT EventDate, WorkflowCat, ErrorType, SUM(EventCount) AS 'Total'
FROM
(
SELECT DATEADD(ww,
DATEPART(ww, e.event_date) - 1,
CONVERT(DATETIME,
CONVERT(VARCHAR(4), DATEPART(yy, e.event_date)) + '-01-01')) AS 'EventDate' ,
c.setting_secondary AS 'WorkflowCat' ,
d.setting_main AS 'ErrorType',
e.event_summary as 'EventSummary'
e.event_count AS 'EventCount'
FROM marlin.support_events AS e
INNER JOIN marlin.support_config AS c
ON e.event_category = c.setting_code
AND config_code = 60
INNER JOIN marlin.support_config AS d
ON e.event_type = d.setting_code
AND d.config_code = 70
WHERE e.event_date BETWEEN DATEADD(MONTH, -2, GETDATE()) AND GETDATE()
AND c.setting_secondary = 'Expenditure Voucher'
AND d.setting_main IN ( 'Unstarted' , 'Timeout' )
)
GROUP BY EventDate, WorkflowCat, ErrorType, EventSummary

Related

GROUP BY & SUM of values with missing MONTHS

I have gone through a lot of examples and joined couple of them in order to come down to the following statement;
DECLARE #StartDate SMALLDATETIME, #EndDate SMALLDATETIME;
SELECT #StartDate = '20170930', #EndDate = '20180930';
;WITH d(d) AS
(
SELECT DATEADD(MONTH, n, DATEADD(MONTH, DATEDIFF(MONTH, 0, #StartDate), 0))
FROM ( SELECT TOP (DATEDIFF(MONTH, #StartDate, #EndDate) + 1)
n = ROW_NUMBER() OVER (ORDER BY [object_id]) - 1
FROM sys.all_objects ORDER BY [object_id] ) AS n
)
SELECT
[Period] = CONVERT(VARCHAR(4), YEAR(d.d)) + '-' + CONVERT(VARCHAR(2), MONTH(d.d)),
QtyTotal = ISNULL(SUM(o.QEXIT),0)
FROM d LEFT OUTER JOIN VE_STOCKTRANS AS o
ON o.TRANSDATE >= d.d
AND o.TRANSDATE < DATEADD(MONTH, 1, d.d)
WHERE STOCKID = 6000 AND TRANSTYPE = 3553
GROUP BY d.d
ORDER BY d.d;
I need to get the total sales quaantity of an item for the past year. If the item does not have any sales for that particular month, 0 should be displayed next to that month. The above query does what is required unless the WHERE clause is provided. As soon as I add the WHERE clause to get the data for a specific product, the months with no sales dissappears.
I would be grateful if an experienced SQL developer can show me the right direction on this.
Thanks
You need to move condtition to ON:
-- ...
SELECT
[Period] = CONVERT(VARCHAR(4),YEAR(d.d)) +'-'+ CONVERT(VARCHAR(2), MONTH(d.d)),
QtyTotal = ISNULL(SUM(o.QEXIT),0)
FROM d LEFT OUTER JOIN VE_STOCKTRANS AS o
ON o.TRANSDATE >= d.d
AND o.TRANSDATE < DATEADD(MONTH, 1, d.d)
AND STOCKID = 6000 AND TRANSTYPE = 3553 -- here
GROUP BY d.d
ORDER BY d.d;
A more generic approach is to apply the filter before you join.
;WITH d(d) AS
(
SELECT DATEADD(MONTH, n, DATEADD(MONTH, DATEDIFF(MONTH, 0, #StartDate), 0))
FROM ( SELECT TOP (DATEDIFF(MONTH, #StartDate, #EndDate) + 1)
n = ROW_NUMBER() OVER (ORDER BY [object_id]) - 1
FROM sys.all_objects ORDER BY [object_id] ) AS n
),
o AS
(
SELECT *
FROM VE_STOCKTRANS
WHERE STOCKID = 6000
AND TRANSTYPE = 3553
)
SELECT
[Period] = CONVERT(VARCHAR(4), YEAR(d.d)) + '-' + CONVERT(VARCHAR(2), MONTH(d.d)),
QtyTotal = ISNULL(SUM(o.QEXIT),0)
FROM
d
LEFT OUTER JOIN
o
ON o.TRANSDATE >= d.d
AND o.TRANSDATE < DATEADD(MONTH, 1, d.d)
GROUP BY
d.d
ORDER BY
d.d;
It's not strictly necessary here, as you've seen in the other answer. When doing FULL OUTER JOIN or other complex queries, however, it can be extremely helpful to filter your sources in one scope and join in a separate scope.
(I always filter my sources, I hate lumpy ketchup.)

Efficient sql subquery on same table based off datetime value

Below I have a simple query to get all the movie ratings for today joining an "event" table and "movie" table.
Select e.*, m.moviename
From Event e, movie m
Where e.eventdate >= DATEADD(day, -1, GETDATE())
and e.moviekey = m.moviekey
order by e.Ratings desc;
Question
In the example above, how would you retrieve the ratings from 1 week ago, and 1 month ago. So the query would return 2 extra columns RatingOneMonthAgo, RatingsOneWeekAgo,etc.
I've looked into subqueries and it's not clicking any help would be appreciated.
Thanks
You could use CTEs to pull this information in (similar to using subqueries).
The following query assumes that you having ratings for every day, and no duplicates (multiple ratings for the same movie on the same day):
WITH cteOneWeekAgo
AS
(
SELECT
moviekey
, Ratings
FROM Event
WHERE CAST(eventdate AS date) = DATEADD(WEEK, -1, CAST(GETDATE() AS date))
)
,
cteOneMonthAgo
AS
(
SELECT
moviekey
, Ratings
FROM Event
WHERE CAST(eventdate AS date) = DATEADD(MONTH, -1, CAST(GETDATE() AS date))
)
SELECT
e.*
, m.moviename
, w.Ratings Ratings_OneWeekAgo
, mth.Ratings Ratings_OneMonthAgo
FROM
Event e
JOIN movie m ON e.moviekey = m.moviekey
LEFT JOIN cteOneWeekAgo w ON e.moviekey = w.moviekey
LEFT JOIN cteOneMonthAgo mth ON e.moviekey = mth.moviekey
WHERE e.eventdate >= DATEADD(DAY, -1, GETDATE())
ORDER BY e.Ratings DESC
I also wrote a more complex query, which will pull in the most recent ratings for the movie before the date you're looking for if ratings for that date don't exist.
WITH cteOneWeekAgo
AS
(
SELECT
moviekey
, Ratings
, eventdate
FROM
(
SELECT
moviekey
, Ratings
, eventdate
, ROW_NUMBER() OVER (PARTITION BY moviekey ORDER BY eventdate DESC) R
FROM Event
WHERE CAST(eventdate AS date) <= DATEADD(WEEK, -1, CAST(GETDATE() AS date))
) Q
WHERE R = 1
)
,
cteOneMonthAgo
AS
(
SELECT
moviekey
, Ratings
, eventdate
FROM
(
SELECT
moviekey
, Ratings
, eventdate
, ROW_NUMBER() OVER (PARTITION BY moviekey ORDER BY eventdate DESC) R
FROM Event
WHERE CAST(eventdate AS date) <= DATEADD(MONTH, -1, CAST(GETDATE() AS date))
) Q
WHERE R = 1
)
SELECT
e.*
, m.moviename
, w.eventdate Ratings_OneWeekAgo_MostRecentDate
, w.Ratings Ratings_OneWeekAgo
, mth.eventdate Ratings_OneMonthAgo_MostRecentDate
, mth.Ratings Ratings_OneMonthAgo
FROM
Event e
JOIN movie m ON e.moviekey = m.moviekey
LEFT JOIN cteOneWeekAgo w ON e.moviekey = w.moviekey
LEFT JOIN cteOneMonthAgo mth ON e.moviekey = mth.moviekey
WHERE e.eventdate >= DATEADD(DAY, -1, GETDATE())
ORDER BY e.Ratings DESC

Pivot and INNER JOINs

I have been trying to run a pivot query but I am failing hard, I am very new with all this so please be patient
what I want is to return the Quantities values of each month, jan, feb... dec, for each PartRef
this is what I have
SELECT PartRef
, Year
, fMonth
, sum(Quantity) as Quantity
FROM(SELECT PartRef
, year(DateClosed) as Year
, month(DateClosed) as Month
, SUM(fldShipped) as Quantity
FROM PartsInvoice
INNER JOIN Requests ON PartsInvoice.fID = Requests.WorkItemRef
INNER JOIN PartsLine ON Requests.ID = PartsLine.RequestRef
WHERE Closed = 1 and DateClosed > DateAdd(mm, DateDiff(mm, 0, GetDate()) -12, 0)
GROUP BY PartRef, year(DateClosed), month(DateClosed)
) as SalesHits
PIVOT (
SUM(NOT SURE)FOR NOT SURE IN ([Jan],[Feb],[Mar],[Apr],[May],[June],[July],[Ago],[Sep],[Oct],[Nov],[Dec])
)AS Hits
GROUP BY PartRef, Year, Month
Here you have an example how it works with a table like yours.
declare #table table(
partref int,
year int,
month nvarchar(50),
quantity int
)
insert into #table values
(1,2016,'jan',12),
(1,2016,'feb',12),
(2,2016,'jan',12),
(2,2016,'feb',12),
(1,2016,'jan',12)
select PartRef
, year
, sum([jan]) 'Jan',sum([feb]) 'Feb'
,sum([mar]),sum([apr]),sum([may]),sum([jun]),sum([jul])
,sum([aug]),sum([sep]),sum([oct]),sum([nov]),sum([dec])
from(
SELECT PartRef
, year
, [jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct],[nov],[dec]
from #table
PIVOT (
SUM(quantity)FOR month IN ([jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct],[nov],[dec])
)AS Hits
) as t
group by PartRef,year
here is the full scope of my query and I believe I got it to work :)
SELECT *
FROM(SELECT PartRef
, year(DateClosed) as Year
, month(DateClosed) as Month
, SUM(Shipped) as Quantity
FROM PartsInvoice
INNER JOIN Requests ON PartsInvoice.ID = Requests.WorkItemRef
INNER JOIN PartsLine ON Requests.ID = PartsLine.RequestRef
WHERE HasClosed = 1 and DateClosed > DateAdd(mm, DateDiff(mm, 0, GetDate()) -13, 0)
GROUP BY PartRef, year(DateClosed), month(DateClosed)
UNION ALL
--RO
SELECT PartRef
, year(DateClosed) as Year
, month(DateClosed) as Month
, SUM(Shipped) as Quantity
FROM RepairOrder
INNER JOIN Requests ON RepairOrder.ID = Requests.WorkItemRef
INNER JOIN PartsLine ON Requests.ID = PartsLine.RequestRef
WHERE Status = 3 and DateClosed > DateAdd(mm, DateDiff(mm, 0, GetDate()) -13, 0)
GROUP BY PartRef, year(DateClosed), month(DateClosed)
UNION ALL
-- Historical Hits
SELECT PartRef
, year(date) as Year
, month(Date) as Month
, SUM(Quantity) as Quantity
FROM PartsHistoricalHits
WHERE Date > DateAdd(mm, DateDiff(mm, 0, GetDate()) -13, 0)
GROUP BY PartRef, year(Date), month(Date)
) as SalesHits
PIVOT (
COUNT (Quantity)FOR fldMonth IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13])
)AS Hits

Sql Sales Report

I am trying to make a report for sales. This is what I have so far but I need to break it down into stores. There is a field in the orders table for storeid. I would like to return the totals for each store. Can anyone point me in the right direction for this?
select DAY(d.date) as Day, MONTH(d.date) as Month, YEAR(d.date) as year, isnull(t.amnt, 0) as [Total Sales] from (
SELECT
sum(o.OrderTotal) amnt,
DAY(o.OrderDate) as 'Day',
YEAR(o.OrderDate) as 'Year',
MONTH(o.OrderDate) as 'Month'
FROM [Orders] o
where
o.OrderDate > #StartDate + ' 00:00:00' and o.OrderDate < '' + #EndDate + ' 23:59:59'
group by YEAR(o.OrderDate), Month(o.OrderDate), DAY(o.OrderDate)
) t
right join (
select dateadd(dd, -number, getdate()) as date
from master.dbo.spt_values
where type = 'p' and number < DATEDIFF(d, #StartDate, #EndDate) +1
) d on year(d.date) = t.[year] and month(d.date) = t.[month] and day(d.date) = t.[day]
order by YEAR(d.date), MONTH(d.date), DAY(d.date)
Add storeId to the GROUP BY clause and SELECT clause.
select DAY(d.date) as Day, MONTH(d.date) as Month, YEAR(d.date) as year, isnull(t.amnt, 0) as [Total Sales], o.storeId from (
SELECT
sum(o.OrderTotal) amnt,
DAY(o.OrderDate) as 'Day',
YEAR(o.OrderDate) as 'Year',
MONTH(o.OrderDate) as 'Month'
FROM [Orders] o
where
o.OrderDate > #StartDate + ' 00:00:00' and o.OrderDate < '' + #EndDate + ' 23:59:59'
group by YEAR(o.OrderDate), Month(o.OrderDate), DAY(o.OrderDate), o.storeId
) t
right join (
select dateadd(dd, -number, getdate()) as date
from master.dbo.spt_values
where type = 'p' and number < DATEDIFF(d, #StartDate, #EndDate) +1
) d on year(d.date) = t.[year] and month(d.date) = t.[month] and day(d.date) = t.[day]
order by YEAR(d.date), MONTH(d.date), DAY(d.date)

How can I merge two rows in a result but not all results?

I have the following query:
-- Compare current period to historical data
select Name ,
avg(TimeProcessing + TimeRendering + TimeDataRetrieval) / 1000 as 'Current Month' ,
isnull(count(TimeProcessing), 0) as 'Sample' ,
min(l2.[Avg_Exec_Time_Previous_Month]) as 'Previous Month' ,
isnull(min(l2.[Executions_Last_Month]), 0) as 'Sample' ,
min(l3.[Avg_Exec_Time_Two_Months_Ago]) as 'Two Months ago' ,
isnull(min(l3.[Executions_Two_Months_Ago]), 0) as 'Sample'
from marlin.report_execution_log l
inner join marlin.report_catalog c on l.ReportID = c.ItemID
left outer join (
select
l2.ReportID ,
(
avg(l2.TimeProcessing + l2.TimeRendering
+ l2.TimeDataRetrieval) / 1000
) as 'Avg_Exec_Time_Previous_Month' ,
count(l2.TimeProcessing) as 'Executions_Last_Month'
from
marlin.report_execution_log l2
where
TimeEnd between dateadd(MONTH, -2, getdate())
and dateadd(MONTH, -1, getdate())
group by
l2.ReportID
) l2 on l.ReportID = l2.ReportID
left outer join (
select
l3.ReportID ,
(
avg(l3.TimeProcessing + l3.TimeRendering + l3.TimeDataRetrieval) / 1000
) as 'Avg_Exec_Time_Two_Months_Ago' ,
count(l3.TimeProcessing) as 'Executions_Two_Months_Ago'
from
marlin.report_execution_log l3
where
TimeEnd between dateadd(MONTH, -3, getdate())
and dateadd(MONTH, -2, getdate())
group by
l3.ReportID
) l3 on l.ReportID = l3.ReportID
group by l.ReportID ,
Name
order by 2 desc
Which brings up the following results:
Unfortunately one our reports changed names throughout the month and subsequently I need to merge these two rows. Is this possible? How can I merge two rows? For example, how could I have the first and second row show additive results using the first rows report name?
If I understood it well you just need a case statement in your select and in your group by.. something like
select case when Name = 'Project1' then 'Project1'
when Name = 'Project2' then 'Project1'
else Name
end as NAME
.......
group by case when Name = 'Project1' then 'Project1'
when Name = 'Project2' then 'Project1'
else Name
end
if your case is that now is Project 1 and one month ago was Project 2, you may need to add the date in the case statement (just in case)
select case when Name = 'Project1' and TimeEnd = getdate() then 'Project1'
when Name = 'Project2' and TimeEnd = dateadd(MONTH, -1, getdate()) then 'Project1'
else Name
end as NAME
.......
group by case when Name = 'Project1' and TimeEnd = getdate() then 'Project1'
when Name = 'Project2' and TimeEnd = dateadd(MONTH, -1, getdate()) then 'Project1'
else Name
end
That's the idea.
Edit.
I think you have an option if they get repeated but I dont really like it at all
SELECT NAME, AVG(Current Month) as Current Month, count(Sample) as Sample, min(Previous Month) as Previous Month, min(Sample2) as Sample2, min(Two Months ago) as Two Months ago,
min(Sample3) as Sample3
FROM
(
select Name ,
avg(TimeProcessing + TimeRendering + TimeDataRetrieval) / 1000 as 'Current Month' ,
isnull(count(TimeProcessing), 0) as 'Sample' ,
min(l2.[Avg_Exec_Time_Previous_Month]) as 'Previous Month' ,
isnull(min(l2.[Executions_Last_Month]), 0) as 'Sample2' ,
min(l3.[Avg_Exec_Time_Two_Months_Ago]) as 'Two Months ago' ,
isnull(min(l3.[Executions_Two_Months_Ago]), 0) as 'Sample3'
from marlin.report_execution_log l
inner join marlin.report_catalog c on l.ReportID = c.ItemID
left outer join (
select
l2.ReportID ,
(
avg(l2.TimeProcessing + l2.TimeRendering
+ l2.TimeDataRetrieval) / 1000
) as 'Avg_Exec_Time_Previous_Month' ,
count(l2.TimeProcessing) as 'Executions_Last_Month'
from
marlin.report_execution_log l2
where
TimeEnd between dateadd(MONTH, -2, getdate())
and dateadd(MONTH, -1, getdate())
group by
l2.ReportID
) l2 on l.ReportID = l2.ReportID
left outer join (
select
l3.ReportID ,
(
avg(l3.TimeProcessing + l3.TimeRendering + l3.TimeDataRetrieval) / 1000
) as 'Avg_Exec_Time_Two_Months_Ago' ,
count(l3.TimeProcessing) as 'Executions_Two_Months_Ago'
from
marlin.report_execution_log l3
where
TimeEnd between dateadd(MONTH, -3, getdate())
and dateadd(MONTH, -2, getdate())
group by
l3.ReportID
) l3 on l.ReportID = l3.ReportID
group by l.ReportID ,
Name
)
group by Name
order by 2 desc