PL SQL - newbie - MAX fron table and avg - sql

I have a table of account numbers by date and 24 hourly intervals
ACCT# ; Date ; hour1, hour2, hour3......hour24
there could be as many as 365 days per account# I would like to find the average of all the intervals as well as the as max interval for each acct#. I tried to add sample data but since it is my first post I can't attach it (need+10 posts) –
"customer_number" "date" "est_hb_0000" "est_hb_0100" "est_hb_0200" "est_hb_0300" "est_hb_0400" "est_hb_0500" "est_hb_0600" "est_hb_0700" "est_hb_0800" "est_hb_0900" "est_hb_1000" "est_hb_1100" "est_hb_1200" "est_hb_1300" "est_hb_1400" "est_hb_1500" "est_hb_1600" "est_hb_1700" "est_hb_1800" "est_hb_1900" "est_hb_2000" "est_hb_2100" "est_hb_2200" "est_hb_2300"
Thanks in advance for your help

This SQL should get you close, after you have restructured and populated the table.
Select Customer, Date, HourOfDay, NumAccts
From ActivityStats
Where Customer = 'zzz'
and Date = 'Dt'
and RowNumber < 11
Order By NumAccts Desc

Related

Average price based on dates

I am trying to calculate a weekly average, and add it as a new column along side what I already have. I have added week starting dates and week ending dates as I thought that would be useful (and how I found do it in a more familiar MS Excel environment).
SELECT
settlementdate as Trading_Interval,
rrp as Trading_Interval_QLD_RRP,
NEXT_DAY(TRUNC(settlementdate-7),'MONDAY')AS Week_Starting,
NEXT_DAY(TRUNC(settlementdate),'SUNDAY')AS Week_Ending
FROM fullauth.tradingprice
WHERE settlementdate > to_date('31/12/2019','dd/mm/yyyy')
AND settlementdate <= to_date('01/01/2020','dd/mm/yyyy')
AND regionid = 'QLD1'
ORDER BY settlementdate DESC;
This code returns a table with 4 columns. I want to find the average price of the Trading_Interval_QLD_RRP when the Trading_Interval falls between the Week_Starting and Week_Ending dates and insert/create this weekly price as a new column
Thanks!
You can use AVG as an analytical function as following:
SELECT
settlementdate as Trading_Interval,
rrp as Trading_Interval_QLD_RRP,
NEXT_DAY(TRUNC(settlementdate-7),'MONDAY')AS Week_Starting,
NEXT_DAY(TRUNC(settlementdate),'SUNDAY')AS Week_Ending,
-- required changes as following
AVG(Trading_Interval_QLD_RRP) OVER (PARTITION BY TRUNC(settlementdate,'IW')) AS AVG_RRP
FROM fullauth.tradingprice
WHERE settlementdate > to_date('31/12/2019','dd/mm/yyyy')
AND settlementdate <= to_date('01/01/2020','dd/mm/yyyy')
AND regionid = 'QLD1'
ORDER BY settlementdate DESC;
Also, Note that TRUNC(settlementdate,'IW') and NEXT_DAY(TRUNC(settlementdate-7),'MONDAY') are same.
Cheers!!

sum last n days quantity using sql window function

I am trying to create following logic in Alteryx and data is coming from Exasol database.
Column “Sum_Qty_28_days“ should sum up the values of “Qty ” column for same article which falls under last 28 days.
My sample data looks like:
and I want following output:
E.g. “Sum_Qty_28_days” value for “article” = ‘A’ and date = ‘’2019-10-8” is 8 because it is summing up the “Qty” values associated with dates (coming within previous 28 days) Which are:
2019-09-15
2019-10-05
2019-10-08
for “article” = ‘A’.
Is this possible using SQL window function?
I tried myself with following code:
SUM("Qty") OVER (PARTITION BY "article", date_trunc('month',"Date")
ORDER BY "Date")
But, it is far from what I need. It is summing up the Qty for dates falling in same month. However, I need to sum of Qty for last 28 days.
Thanks in advance.
Yes, this is possible using standard SQL and in many databases. However, this will not work in all databases:
select t.*,
sum(qty) over (partition by article
order by date
range between interval '27 day' preceding and current row
) as sum_qty_28_days
from t;
If your RDBMS does not support the range frame, an alternative solution is to use an inline subquery:
select
t.*,
(
select sum(t1.qty)
from mytable t1
where
t1.article = t.article
and t1.date between t.date - interval 28 days and t.date
) sum_qty_28_days
from mytable t

How to create a dynamic where clause in sql?

So I have created a table that has the following columns from a transaction table with all customer purchase records:
1. Month-Year, 2.Customer ID, 3. Number of Transactions in that month.
I'm trying to create a table that has the output of
1. Month-Year, 2. Number of active customers defined by having at least 1 purchase in the previous year.
The code that I have currently is this but the case when obviously only capturing one date and the where clause isn't dynamic. Would really appreciate your help.
select month_start_date, cust_ID,
(case when month_start_Date between date and add_months(date, -12) then count(cust_ID) else 0 end) as active
from myserver.mytable
where
month_start_Date>add_months(month_start_date,-12)
group by 1,2
EDIT: I'm just trying to put a flag next to a customer if they are active in each month defined as having at least one transaction in the last year thanks!
You might use Teradata's proprietary EXPAND ON synax for creating time series:
SELECT month_start_date, COUNT(*)
FROM
( -- create one row for every month within the next year
-- after a customer's transaction
SELECT DISTINCT
BEGIN(pd) AS month_start_date,
cust_ID
FROM myserver.mytable
EXPAND ON PERIOD(month_start_date, ADD_MONTHS(month_start_date,12)) AS pd
BY ANCHOR MONTH_BEGIN -- every 1st of month
FOR PERIOD (DATE - 500, DATE) -- use this to restrict to a specific date range
) AS dt
GROUP BY month_start_date
ORDER BY month_start_date

IN Clause issue

I have one SQL output table like this
ITEM,LOC,PERIOD,QUANTITY
101,US,07/22/2015,500
101,US,07/02/2015,0
102,LON,07/22/2015,0
102,LON,07/02/2015,1000
But I want the output table as follows,
ITEM LOC 07/22/2015 07/02/2015
101 US 500 0
102 LON 0 1000
Please find the code which I have used below,
select * from
(
select item, loc, period, quantity
from example
)
pivot
(
sum (quantity) for period in ('22/JUL/2015','02/JUL/2015'));
If it is for 2 dates, then no issue in mentionning the 'IN' clause
If it is 1000 dates like weekly, monthly and daily. Then how ?
Below command is not working in 'IN' clause.
SELECT PERIOD FROM EXAMPLE WHERE PERIOD < TO_DATE(22/JUL/2015);
Can you please help me to solve this issue ?
Thanks for your time.
Your issue may be incompatible data types. If the period column on your table is DATE type, you are trying to compare strings/VARCHAR with DATE type.
If period column is a DATE try changing your IN to
SELECT period FROM example WHERE period < DATE '2015-07-22';
or
SELECT period FROM example WHERE period < TO_DATE('22/JUL/2015', 'DD/MON/YYYY');

Display a rolling 12 weeks chart in SSRS report

I am calling the data query in ssrs like this:
SELECT * FROM [DATABASE].[dbo].[mytable]
So, the current week is the last week from the query (e.g. 3/31 - 4/4) and each number represents the week before until we have reached the 12 weeks prior to this week and display in a point chart.
How can I accomplish grouping all the visits for all locations by weeks and adding it to the chart?
I suggest updating your SQL query to Group by a descending Dense_Rank of DatePart(Week,ARRIVED_DATE). In this example, I have one column for Visits because I couldn't tell which columns you were using to get your Visit count:
-- load some test data
if object_id('tempdb..#MyTable') is not null
drop table #MyTable
create table #MyTable(ARRIVED_DATE datetime,Visits int)
while (select count(*) from #MyTable) < 1000
begin
insert into #MyTable values
(dateadd(day,round(rand()*100,0),'2014-01-01'),round(rand()*1000,0))
end
-- Sum Visits by WeekNumber relative to today's WeekNumber
select
dense_rank() over(order by datepart(week,ARRIVED_DATE) desc) [Week],
sum(Visits) Visits
from #MyTable
where datepart(week,ARRIVED_DATE) >= datepart(week,getdate()) - 11
group by datepart(week,ARRIVED_DATE)
order by datepart(week,ARRIVED_DATE)
Let me know if I can provide any more detail to help you out.
You are going to want to do the grouping of the visits within SQL. You should be able to add a calculated column to your table which is something like WorkWeek and it should be calculated on the days difference from a certain day such as Sunday. This column will then by your X value rather than the date field you were using.
Here is a good article that goes into first day of week: First Day of Week