Using days of the week for aggregates in DB2 - sql

I currently have a query that reads from a table which is written to daily, so I have totals for every day.
What I'm trying to do is modify this query so that I can use days of the week as an aggregate, if that makes sense.
THe totals I get right now are correct, but I want to use Sunday through Saturday as a week and effectively say ``'If today is wednesday, sum totals for weeklyData for Sunday, MOnday and Tuesday from tableOne```
I have this query:
SELECT employee,
sum(case when category = 'Brown' then daily_total else 0 end) as DailyBrownNumbers,
sum(case when category = 'Brown' then weekly_quota else 0 end) as WeeklyBrownNumbers,
CURRENT_DATE as DATE_OF_REPORT
from dailyRecords
where date_of_report >= current_date
group by employee
which reads from that table for the daily records and that's what I need still, but I want to add a sum for daily_total based on those days of the week if possible.
Can this be done with DB2?

You can use dayofweek function. SQL gets all records starting from Sunday including current date. Second column "DailyBrownNumbers" uses case statement to restrict totals to current date records. Third column "WeeklyTotal" has totals for all records from Sunday.
SELECT employee,
sum(case when category = 'Brown' and date_of_report >= current date
then daily_total
else 0 end) as DailyBrownNumbers,
sum(case when category = 'Brown'
then daily_total
else 0 end) as WeeklyTotal,
sum(case when category = 'Brown'
then weekly_quota
else 0 end) as WeeklyBrownNumbers,
CURRENT_DATE as DATE_OF_REPORT
from dailyRecords
where date_of_report >= ( current date - ( dayofweek(current date) - 1 ) days )
group by employee

Related

How to get number of Executed, Scheduled and Cancelled bookings per month per year in sqlite?

This is the table and all its fields and I am trying to get the number of executed, scheduled, and cancelled bookings per month per year in SQLite. Can anyone help, please? Thanks
Table fields: {id (INT), starttime(DATESTAMP), duration_hours(INT), user_id(INT), status(TEXT)}
id (booking id) is unique, starttime ranges between 2020 and 2022 (format: yyyy-mm-dd), user_id is not unique, status are either Executed, Scheduled or Cancelled.
You may use the strftime function to extract the month and year from the date value, then use conditional count aggregated by the value of strftime.
Select strftime('%Y-%m', starttime) AS 'Month_Of_Year',
COUNT(Case status When 'Executed' Then 1 Else Null End) AS 'Executed',
COUNT(Case status When 'Scheduled' Then 1 Else Null End) AS 'Scheduled',
COUNT(Case status When 'Cancelled' Then 1 Else Null End) AS 'Cancelled'
From Bookings
Group By strftime('%Y-%m', starttime)
Order By strftime('%Y-%m', starttime)
See a demo from db<>fiddle.

How to calculate average and latest cost of a product over date range in same sql query

I have table where product is there and it's cost over a time range. I need to calculate the average cost over the period, with the latest cost till date to be considered in average also I need to fetch the current cost. How can I achieve it in same query.
Input Table
I am looking for output like
product | average_cost | current_cost
(average cost is (cost*days of that cost)/total days dill today's date.
You can use date arithmetic and conditional aggregation:
select product,
( sum( cost * datediff(day, beg_date, (case when end_date > getdate() then getdate() else end_date end) )) /
sum(datediff(day, beg_date, (case when end_date > getdate() then getdate() else end_date end))
) as avg_price,
max(case when end_date > getdate() then price end)
from t
group by product;

SQL Query : Is it possible to project a four results in a single query?

Currently, I am executing four queries to project the results based last 24hours, last week, last month and last month. Is it possible to project a four results in a single query?
If you need last one week, last one month, last one year compared to current date then you can do it using conditional aggregation in oracle as following:
Select sum(case when trunc(date_col) = trunc(sysdate-1) then 1 end) as last_one_day,
sum(case when trunc(date_col) between trunc(sysdate-7) and trunc(sysdate-1) then 1 end) as last_one_week,
sum(case when trunc(date_col) between trunc(add_months(sysdate,-1)) and trunc(sysdate-1) then 1 end) as last_one_month,
sum(case when trunc(date_col) between trunc(add_months(sysdate,-12)) and trunc(sysdate-1) then 1 end) as last_one_year
From your_table
Where type = ...
Cheers!!

SQL concat case select when trying to add new column of previous month data

I have a data set in which I need to concat month and year for the previous month. the problem is it spans over two years. I need to create a statement in which mean the month - 1 = 0, month becomes 12 and year-1.
Select concat(case
when month > 1 then select(month-1, year)
when month = 1 then select(12, year -1)
else select(month-1, year)
end
as monthyear
from table
You need 2 CASE statements inside concat(), for the month and the year:
select
concat(
case when month > 1 then month - 1 else 12 end,
case when month > 1 then year else year - 1 end
)
If you have month and year as separate columns and want to subtract one month, then you can use:
select (case when month > 1 then year else year - 1 end) as year,
(case when month > 1 then month - 1 else 12 end) as month
Here's a different approach (tried with SQLite3, adjust accordingly to your SQL syntax):
-- some test data first
create table t(yy,mm);
insert into t values
(2018,1),(2018,2),(2018,3),(2018,4),(2018,5),(2018,6),
(2018,7),(2018,8),(2018,9),(2018,10),(2018,11),(2018,12),
(2019,1),(2019,2),(2019,3),(2019,4),(2019,5),(2019,6),
(2019,7),(2019,8),(2019,9),(2019,10),(2019,11),(2019,12),
(2020,1),(2020,2),(2020,3),(2020,4),(2020,5),(2020,6),
(2020,7),(2020,8),(2020,9),(2020,10),(2020,11),(2020,12);
-- current year and month, year of previous month and previous month
select yy,mm,yy-((mm+10)%12+1)/12 as yy_1,(mm+10)%12+1 mm_1 from t;

Grouping by Date without Time component

So i have a table that looks like this:
As you can see some of the dates are the same however the time of day is different.
i have the following select statement (i have deleted and altered some data since this is rather sensitive):
SELECT LAST_UPD AS PERIOD,
COUNT(CASE WHEN SOLVED_SECONDS /60 /60 <= 2 THEN 1 END) as completed_within_2hours,
COUNT(CASE WHEN STATUS ='Færdig' THEN +1 END) as completed_callbacks,
COUNT(CASE WHEN SOLVED_SECONDS /60 /60 <= 2 THEN 1 END) / COUNT(CASE WHEN STATUS ='Færdig' THEN 1 END) * 100 as Percentage
FROM TABLE
WHERE LAST_UPD BETWEEN '2013-07-01' AND '2013-07-03'
AND STATUS ='Færdig'
AND AGENTGROUP IN ('Hovednumre','Forsikring','Hotline','Kunder')
GROUP BY LAST_UPD
Now i want my query to count when the DATES are the same so forexample if the date is 2013-07-01 i want it to count x amount for that day regardless of time of day.
I have tried the following:
SELECT DISTINCT TO_CHAR(LAST_UPD, 'YYYY/MM/DD') AS PERIOD,
Sadly this returns each of days but doesnt count them correctly (it returns 1 for each day).
Perhaps what you want is to select and group by "Trunc(last_upd)"