Dynamic SQL Date Header - stored-procedures

I would like to ask a little help on using dynamic sql date header,
i have data that i count transaction group by date then by hours.
date range would be entered start date and end date.
my data is simple just date and time:
created_Date
'2020-01-14 13:25:20.147'
'2020-01-14 13:23:15.639'
'2020-01-14 12:27:48.896'
'2020-01-09 20:03:06.713'
'2020-01-09 19:33:05.032'
'2020-01-09 19:16:35.590'
'2020-01-09 19:08:19.788'
'2020-01-09 13:02:03.543'
'2020-01-09 12:23:12.595'
'2020-01-08 15:29:52.262'
'2020-01-08 15:17:31.247'
'2020-01-08 15:16:51.499'
'2020-01-08 13:29:47.661'
'2020-01-06 20:19:30.173'
currently found this code:
ALTER PROCEDURE "DBA"."test_trancountdaily"(#sdate datetime, #edate datetime)
BEGIN
create table #trantable(TDate varchar(100),Hour varchar(2), count varchar(1000));
insert #trantable
SELECT CAST(created_date as date) AS ForDate,
DATEPART(hour,created_date) AS OnHour,
COUNT(*) AS Totals
FROM prescription
WHERE created_date >= #sdate and created_date <= #edate
GROUP BY CAST(created_date as date),
DATEPART(hour,created_date)
ORDER BY CAST(created_date as date),
DATEPART(hour,created_date) asc;
select * from #trantable;
END
my data are created_date datetime and would count how many transaction that is inside a Hour
but would like an output like this:
HR
2020-01-01
2020-01-02
2020-01-03 etc
1
1
0
3
2
0
1
1
3
1
1
1
4
1
0
2
thanks
bolivar1985

Sample Result in interactive sql
Good Day,
Just solve query without using pivot in sybase it was mind troubling but got it.
set #sql_date = #sql_date + ', COUNT(CASE WHEN DATE(prescription.created_date) = ''' + #ls_date +
''' AND #time_table.hrs = HOUR(prescription.created_date) THEN prescription.tran_id END) AS
[' + #ls_date + ']' ;
looping the date range to be given by user, and date as header.
bolivar1985

Related

Google Ads Script (AWQL) get custom date range for reporting

I need to pull a google ads report that will get data from a fixed date (28th May) until today and push the data to a spreadsheet. I can't figure out how to define the date range for this query
I've tried googling and reading the google documentation but I can't figure it out
function main() {
var spreadsheet = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/XXX');
var sheet = spreadsheet.getSheetByName('Data')
var report = AdsApp.report(
'SELECT Date, CampaignName, AverageFrequency, Impressions, ImpressionReach ' +
'FROM CAMPAIGN_PERFORMANCE_REPORT ' +
'WHERE Impressions > 0 ' +
'DURING 20190528,TODAY');
sheet.clearContents();
report.exportToSheet(sheet);
}
I need to use today as the end date instead of the campaign end date as the end date for this query as I'm trying to pull frequency as a metric and it will just show blank values if the end date is in the future.
Please let me know if there is a way to make the query work. Thanks!
The TODAY keyword acts as the "full range" of the DURING property and cannot be used as the end part (as far as I know). The following should work.
function main() {
var endDate = new Date();
var endRange = Utilities.formatDate(endDate, 'America/Chicago', 'YYYYMMdd');
var spreadsheet = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/XXX');
var sheet = spreadsheet.getSheetByName('Data')
var report = AdsApp.report(
'SELECT Date, CampaignName, AverageFrequency, Impressions, ImpressionReach ' +
'FROM CAMPAIGN_PERFORMANCE_REPORT ' +
'WHERE Impressions > 0 ' +
'DURING 20190528,' + endRange);
sheet.clearContents();
report.exportToSheet(sheet);
}
Date ranges for the report are defined in the DURING clause of the query. Date ranges can be specified in two different ways:
A custom date range using regular AWQL syntax, for example:
SELECT Id, Criteria, AdGroupName
FROM KEYWORDS_PERFORMANCE_REPORT
DURING 20190101,20190325
A date range type, for example:
SELECT Id, Criteria, AdGroupName
FROM KEYWORDS_PERFORMANCE_REPORT
DURING LAST_7_DAYS
In your case you should use:
DURING 20190528, 20190723
There is no other option for you to do that.

Get total count of sql records of matched date

I'm trying to return a count of records from a database with today's date, using entity framework. I think my query is ok, if you take a look at the screenshot record 2 is the only item out of the 3 with todays date, which is correct.
How can i return a count. Currently its returning a bool value
Thank you
Dim today = DateTime.Today.Date
Dim todaysBuild = retrieveOrders.[Select](Function(build) build.TimeAndDate >= today).ToList()
EDIT:
Dim todaysBuild = retrieveOrders.Where(Function(build) build.TimeAndDate >= today).ToList()
The variable todaysBuild is a list. You need the count (Integer) of that list so add the .Count at the end of your code.
Dim todaysBuild = retrieveOrders.[WHERE](Function(build) build.TimeAndDate >= today).ToList.Count

SQL Join for two scripts

I am trying to join two script
--script 1
select
t.vendor_code,
RTRIM(LTRIM(cast(datename(month, [CLOSED_DATE]) as char(15))))+',' + RTRIM(LTRIM(cast(year([CLOSED_DATE]) as char(20)))) as [CLOSED_DATE],
count(t.vendor_code) as [No_of_Case]
from
dbo.FTX_FA_CASE t WITH (NOLOCK)
where
[CLOSED_DATE] is not null
group by
t.vendor_code, CLOSED_DATE
and
--script 2
SELECT
(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20)))) + ',')
FROM
efoxsfc.dbo.FTX_FA_Calender
WHERE
1 = 1
AND CAST(dates AS DATETIME) >= DATEADD(mm, -5 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0))
AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)
which return data like this:
I want a single script which return this output:
Basically I am trying to get all the data of second table and no_of_Case from 1st table. The month which is not present in 1st script , for that no_of_case value should be "0".
Please advice !!
Try this
select
name,
(select distinct date
from Table_1 t2
where t1.date = t2.date),
count([no of count])
from
Table_1 t1
group by
name, date

Get corresponding values to a select in a group for PostgreSQL

(Background: I'm attempting to find the "peak" hour of activity in a series of cameraapis, defined as having the most entries with a start and end date between 1 hour periods (starting with the beginning of the hour) For example, 1:00 to 2:00 may have 8 entries within that timeframe, but 2:00 to 3:00 has 12 entries - so I would want to have it return the 12 entry timeframe.)
I'm having trouble getting associated data from a SELECT query of a group. Here is the code:
def reach_peak_hour_by_date_range(start_date, end_date)
placement_self_device_id = self.device_id
query = <<-SQL
SELECT max(y.num_entries) AS max_entries
FROM
(
SELECT x.starting_hour, count(*) AS num_entries
FROM
(
SELECT date_trunc('hour', visitor_start_time) starting_hour
FROM Cameraapis WHERE device_id = '#{placement_self_device_id}'::text AND visitor_start_time > '#{start_date}'::timestamp AND visitor_end_time < '#{end_date}'::timestamp
) AS x
GROUP BY x.starting_hour
) AS y
SQL
results = Placement.connection.execute(query)
binding.pry
end
Cameraapi have a device_id, visitor_start_time, and visitor_end_time, referenced in the code.
This code successfully returns the max_entries in a 1 hour period, but I can't figure out what to SELECT to get the associated starting_hour to that max_entries. Because it is a group, it requires aggregated functions, which I don't actually need. Any advice?
didnt quite understand the question ... use window functions
select starting_hour , num_entries from (
SELECT starting_hour ,y.num_entries, max(y.num_entries) over() AS max_entries
FROM
(
SELECT x.starting_hour, count(*) AS num_entries
FROM
(
SELECT date_trunc('hour', visitor_start_time) starting_hour
FROM Cameraapis WHERE device_id = '#{placement_self_device_id}'::text AND visitor_start_time > '#{start_date}'::timestamp AND visitor_end_time < '#{end_date}'::timestamp
) AS x
GROUP BY x.starting_hour
) AS y
) as u
where num_entries = max_entries
this query returns all entries associated with peak hour, you can modify it to return only entry count with associated hour selecting hour and count using distinct or grouping
select * from
(
select x.*, max(num_entries) over()as max_num_entries from
(
SELECT Cameraapis.* ,date_trunc('hour', visitor_start_time) as starting_hour, count(*) over( partition by date_trunc('hour', visitor_start_time)) as num_entries
FROM Cameraapis WHERE device_id = '#{placement_self_device_id}'::text AND visitor_start_time > '#{start_date}'::timestamp AND visitor_end_time < '#{end_date}'::timestamp
) as x
) as x where max_num_entries = num_entries

PLSQL new salary is not displaying or displaying wrong

Thanks, for idea
I have to write a procedure that computes number of project, and
average working hours of employees where employee id is passed as a
parameter to the procedure. If the average working hours is less than
10 then employee’s salary remain the same, otherwise check if number
of project is less than 4 then 5% of salary, else 10% of salary is
added to the salary.
something wrong with my output in plsql statement it is not displaying
new salary
here is my plsql procedure:
create or replace procedure view_data(p_id number) is
cursor c1
is
select count(distinct a.projectid) as PRJ_COUNT, e.empid, e.empname, e.salary as old_sal, round(avg(a.hours),0)as AVG_HOURS
from assignment a join employee e
on a.empid=e.empid
where e.empid=p_id
group by e.empid,e.empname, e.salary;
creader c1%rowtype;
cursor c2
is
select empid, salary as new_sal
from employee
where empid=p_id for update of salary;
rate_rec c2%rowtype;
v_new_salary number;
begin
--open c1;
--fetch c1 into creader;
for creader in c1 loop
for rate_rec in c2 loop
if creader.avg_hours < 10 then
update employee set salary=rate_rec.new_sal
where empid=rate_rec.empid;
elsif creader.prj_count<4 then
update employee set salary=rate_rec.new_sal+rate_rec.new_sal*0.05
where empid=rate_rec.empid;
else
update employee set salary=rate_rec.new_sal+rate_rec.new_sal*0.1
where empid=rate_rec.empid;
end if;
select salary into v_new_salary from employee
where empid=creader.empid;
dbms_output.put_line('Employee ID: '||creader.empid);
dbms_output.put_line('Employee Name: '||creader.empname);
dbms_output.put_line('Number of projects: '||creader.prj_count);
dbms_output.put_line('Average Working Hours: '||creader.avg_hours);
dbms_output.put_line('Old Salary: '||rate_rec.new_sal);
dbms_output.put_line('New Salary: '||v_new_salary);
end loop;
end loop;
end view_data;
/
here is the output:
Employee ID: 101
Employee Name: Marlen
Number of projects: 3
Average Working Hours: 87
Old Salary: 39206
New Salary: 41166
solution with using cursors:
create or replace procedure view_data(p_id number) is
cursor c1
is
select count(distinct a.projectid) as PRJ_COUNT, e.empid, e.empname, e.salary as old_sal, round(avg(a.hours),0)as AVG_HOURS
from assignment a join employee e
on a.empid=e.empid
where e.empid=p_id
group by e.empid,e.empname, e.salary;
creader c1%rowtype;
cursor c2
is
select empid, salary as new_sal
from employee
where empid=p_id for update of salary;
rate_rec c2%rowtype;
v_new_salary number;
v_bonus number;
begin
for creader in c1 loop
for rate_rec in c2 loop
if creader.avg_hours >= 10 then
if creader.prj_count<4 then
update employee set salary=salary*1.05
where empid=rate_rec.empid
return salary into v_new_salary;
else
update employee set salary=salary*1.1
where empid=rate_rec.empid
returning salary into v_new_salary;
end if;
end if;
v_bonus:=v_new_salary-rate_rec.new_sal;
dbms_output.put_line('Employee ID: '||creader.empid);
dbms_output.put_line('Employee Name: '||creader.empname);
dbms_output.put_line('Number of projects: '||creader.prj_count);
dbms_output.put_line('Average Working Hours: '||creader.avg_hours);
dbms_output.put_line('Old Salary: '||creader.old_sal);
dbms_output.put_line('Bonus: '||v_bonus);
dbms_output.put_line('New Salary: '||v_new_salary);
end loop;
end loop;
end view_data;
/
The variable rate_rec is in scope in the loop, not outside. You should put all your put_line inside the loop.
rate_rec.new_sal is the old salary. The new one will be updated in the table, not in the record with the previous salary.
I propose that you do your updates and then you select once again and check that is has been modified. You could also use a returning clause in the updates to get the new salary.
Here is a possible solution. I have not checked thoroughly the query. There should probably be a commit at the end of the procedure.
set serveroutput on
create or replace procedure update_data(p_id number) is
prj_count integer;
avg_hours integer;
old_salary number;
new_salary number;
begin
select count(a.projectid), round(avg(a.hours),0), e.salary
into prj_count, avg_hours, old_salary
from assignment a join employee e on a.empid=e.empid
where e.empid=p_id
group by e.salary;
new_salary := old_salary;
if avg_hours >= 10 then
if prj_count<4 then
update employee set salary=salary+salary*0.05
where empid=p_id
returning salary into new_salary;
else
update employee set salary=salary+salary*0.1
where empid=p_id
returning salary into new_salary;
end if;
end if;
dbms_output.put_line('Old salary: ' || old_salary);
dbms_output.put_line('New salary: ' || new_salary);
end update_data;
/

Resources