How to find the max number of a average? - coldfusion

Im new to using coldfusion and I'm trying to figure out how i can output the max number of a average. Right now i can find the average for a specific department, but how would I from that data get the max number from that list and display the max average number?
here is my code
<tr>
<td>#csedept_name#</td>
<td><div align="right">#totalcount#</div></td>
<td><div align="right"><cfif totalstars eq ''>–<cfelse>#totalstars#</cfif></div></td>
<td><div align="right"><cfif totalstarsgiven eq ''>–<cfelse>#totalstarsgiven#</cfif></div></td>
<td><div align="right"><cfif totalstars eq ''>–<cfelse><cfset avgstars = totalstars / totalcount>#DecimalFormat(avgstars)#</cfif></div></td>
</tr>
<cfset countEmployees = countEmployees + totalcount>
<cfif totalstarsgiven neq ''><cfset countStarsGiven = countStarsGiven + totalstarsgiven></cfif>
<cfif totalstars neq ''>
<cfset countStarsReceived = countStarsReceived + totalstars>
<cfset countStarAverage = countStarAverage + avgstars>
</cfif>
.....
<th><div align="right">#countEmployees#</div></th>
<th><div align="right">#countStarsReceived#</div></th>
<th><div align="right">#countStarsGiven#</div></th>
<th><div align="right">#avgstars#</div></th> //here to display the max of the average
Here is the query code:
<h1><cfoutput>#self#</cfoutput></h1>
<cfquery datasource="Intranet" name="GetDepartments">
SELECT * FROM CSEReduxDepts
</cfquery>
<cfquery datasource="Intranet" name="GroupStars">
SELECT execoffice_status, employeedept, COUNT(*) as 'totalstars'
FROM CSEReduxResponses
WHERE execoffice_status = 1
GROUP BY execoffice_status, employeedept
</cfquery>
<cfquery dbtype="query" name="GetTotalStars">
SELECT *
FROM GroupStars, GetDepartments
WHERE GroupStars.employeedept = GetDepartments.csedept_id
</cfquery>
<cfif GetTotalStars.RecordCount gt 0>
<cfquery datasource="PhoneList" name="GetAllData">
SELECT dept.csedept_id, COUNT(*) as 'totalcount'
FROM employee, dept
WHERE employee.dept_id = dept.dept_id
AND employee.emp_status = 1
AND dept.csedept_id is not null
GROUP BY dept.csedept_id
</cfquery>
<cfquery dbtype="query" name="GetDepartmentTotalEmployeesCount">
SELECT *
FROM GetAllData, GetDepartments
WHERE GetAllData.csedept_id = GetDepartments.csedept_id
</cfquery>
<cfquery name="joinQuery" dbtype="query" >
SELECT *
FROM GetTotalStars
WHERE GetTotalStars.csedept_id = -1
</cfquery>
<cfset QueryAddRow(joinQuery)>
<cfquery name="GetUnion" dbtype="query" >
SELECT *
FROM GetDepartmentTotalEmployeesCount, GetTotalStars
WHERE GetDepartmentTotalEmployeesCount.csedept_id = GetTotalStars.csedept_id
UNION
SELECT GetDepartmentTotalEmployeesCount.*, joinQuery.*
FROM GetDepartmentTotalEmployeesCount, joinQuery
WHERE GetDepartmentTotalEmployeesCount.csedept_id NOT IN (#ValueList(GetTotalStars.csedept_id)#)
</cfquery>
<cfquery datasource="Intranet" name="GroupStarsGiven">
SELECT execoffice_status, submitterdept, COUNT(*) as 'totalstarsgiven'
FROM CSEReduxResponses
WHERE execoffice_status = 1
GROUP BY execoffice_status, submitterdept
</cfquery>
<cfquery dbtype="query" name="GetTotalStarsGiven">
SELECT *
FROM GroupStarsGiven, GetDepartments
WHERE GroupStarsGiven.submitterdept = GetDepartments.csedept_id
</cfquery>
<cfquery name="joinQuery2" dbtype="query" >
SELECT *
FROM GetTotalStarsGiven
WHERE GetTotalStarsGiven.csedept_id = -1
</cfquery>
<cfset QueryAddRow(joinQuery2)>
<cfquery name="GetUnion2" dbtype="query" >
SELECT *
FROM GetUnion, GetTotalStarsGiven
WHERE GetUnion.csedept_id = GetTotalStarsGiven.csedept_id
UNION
SELECT GetUnion.*, joinQuery2.*
FROM GetUnion, joinQuery2
WHERE GetUnion.csedept_id NOT IN (#ValueList(GetTotalStarsGiven.csedept_id)#)
ORDER BY csedept_name ASC
</cfquery>

Generally speaking, you can do this with sql. The general idea is
select dept, max(number) maxnumber, avg(number) avgnumber
from department join
(select deptid, number
from department
where clause
) temp on department.deptid = temp.deptid
where clause
group by dept
Make sure the two where clauses are the same.

There are a couple of ways to skin this cat. I apologize if you like cats.
First, you can do it the way Dan suggested. Simple enough, right?
Second, and I do not recommend it over the other.
<cfset maxNum = ArrayMax(query['columnname']) />
but it is an option

Related

Redshift Error when executing the delete script with EXISTS function. The Select runs fine for this query

This Redshift query fails -
DELETE FROM TBL_1 stg
WHERE EXISTS (
WITH CCDA as (
SELECT
row_number() OVER (PARTITION BY emp_id,customer_id ORDER BY seq_num desc) rn
, *
FROM TBL_2
WHERE end_dt > (SELECT max(end_dt) FROM TBL_3)
)
SELECT emp_id,customer_id FROM CCDA WHERE rn = 1
AND stg.emp_id = CCDA.emp_id
AND stg.customer_id = CCDA.customer_id
);
Error: Invalid operation: syntax error at or near "stg"
However, the below query runs fine -
SELECT * FROM TBL_1 stg
WHERE EXISTS (
WITH CCDA as (
SELECT
row_number() OVER (PARTITION BY emp_id,customer_id ORDER BY seq_num desc) rn
, *
FROM TBL_2
WHERE end_dt > (SELECT max(end_dt) FROM TBL_3)
)
SELECT emp_id,customer_id FROM CCDA WHERE rn = 1
AND stg.emp_id = CCDA.emp_id
AND stg.customer_id = CCDA.customer_id
);
Am I missing something?
You cannot use an alias in a DELETE statement for the target table. "stg" cannot be used as the alias and this is why you are getting this error.
Also to reference other tables in a DELETE statement you need to use the USING clause.
See: https://docs.aws.amazon.com/redshift/latest/dg/r_DELETE.html
A quick stab of what this would look like (untested):
WITH CCDA as (
SELECT
row_number() OVER (PARTITION BY emp_id,customer_id ORDER BY seq_num desc) rn
, *
FROM TBL_2
WHERE end_dt > (SELECT max(end_dt) FROM TBL_3)
)
DELETE FROM TBL_1
USING CCDA
WHERE CCDA.rn = 1
AND TBL_1.emp_id = CCDA.emp_id
AND TBL_1.customer_id = CCDA.customer_id
;

Convert ColdFusion Date to Unix timestamp

How can I convert a ColdFusion date to Unix Timestamp?
myDate = DateAdd("m", -1, Now());
I would like to convert myDate to unix timestamp using ColdFusion
Thanks
Just create the UNIX origin date, and do a DateDiff from then to now (or whatever your date variable is) in seconds.
<cfset startDate = createdatetime( '1970','01','01','00','00','00' )>
<cfset datetimeNow = dateConvert( "local2Utc", now() )>
<cfset UnixStamp = datediff( 's', startdate, datetimeNow )>
Since CF stores DateTime objects as Java Date objects, this also works:
var unixStamp = int( now().getTime() / 1000 );
getTime() returns milliseconds, which is why I divided by 1000 and rounded using int().
So, specifically for the example in the OP:
var unixStamp = int( myDate.getTime() / 1000 );

How do i get table name and column name using sequence name in postgres?

I know the sequence name but I don't know the table name and column name of it.
So please help me how to find it.
Slight improvisation using #a_horse_with_no_name's answer. The below query will also give the schema name and sequence name. So, this gives you the data with schema,table,column and sequence names as single result
select ts.nspname as object_schema,
tbl.relname as table_name,
col.attname as column_name,
s.relname as sequence_name
from pg_class s
join pg_namespace sn on sn.oid = s.relnamespace
join pg_depend d on d.refobjid = s.oid and d.refclassid='pg_class'::regclass
join pg_attrdef ad on ad.oid = d.objid and d.classid = 'pg_attrdef'::regclass
join pg_attribute col on col.attrelid = ad.adrelid and col.attnum = ad.adnum
join pg_class tbl on tbl.oid = ad.adrelid
join pg_namespace ts on ts.oid = tbl.relnamespace
where s.relkind = 'S'
-- and s.relname = 'your_sequence_name_here'
and d.deptype in ('a', 'n');
Assuming it's a sequence that is owned by a column e.g. because the column is defined as serial or identity then you can get that information by looking at pg_depend and join that to pg_class (and others)
select tbl.relname as table_name,
col.attname as column_name
from pg_class s
join pg_namespace sn on sn.oid = s.relnamespace
join pg_depend d on d.refobjid = s.oid and d.refclassid='pg_class'::regclass
join pg_attrdef ad on ad.oid = d.objid and d.classid = 'pg_attrdef'::regclass
join pg_attribute col on col.attrelid = ad.adrelid and col.attnum = ad.adnum
join pg_class tbl on tbl.oid = ad.adrelid
join pg_namespace ts on ts.oid = tbl.relnamespace
where s.relkind = 'S'
and s.relname = 'your_sequence_name_her'
and d.deptype in ('a', 'n');
Another option is to look at the default value of the columns and check if it contains the sequence name:
select tbl.relname as table_name,
col.attname as column_name
from pg_attrdef ad
join pg_attribute col on col.attrelid = ad.adrelid and col.attnum = ad.adnum
join pg_class tbl on tbl.oid = ad.adrelid
where pg_get_expr(ad.adbin, ad.adrelid) like '%your_sequence_name_here%'
This would also work for sequences that are not owned by a column.

From Select in doctrine 2

How do I do this in doctrine2 QB or DQL.
SELECT * FROM
(
select * from my_table order by timestamp desc
) as my_table_tmp
group by catid
order by nid desc
I think your query is the same as:
SELECT *
FROM my_table
GROUP BY catid
HAVING timestamp = MAX(timestamp)
ORDER BY nid DESC
;
If it is correct, then you should be able to do:
$qb->select('e')
->from('My\Entities\Table', 'e')
->groupBy('e.catid')
->having('e.timestamp = MAX(e.timestamp)')
->orderBy('nid', 'DESC')
;
Or, directly using DQL:
SELECT e
FROM My\Entities\Table e
GROUP BY e.catid
HAVING e.timestamp = MAX(e.timestamp)
ORDER BY e.nid DESC
;
Hope this helps and works! ;)

Need help on Regular expression to extract sql sub query

i am new to regx...i want to get the subquery from given query using regular expression.
For example i have query like following
Select * from (
select * from Table_A where ID = 90
UNION
select * from Table_B where ID = 90
) as SUBQUERY left join TABL_ABC abc ON (abc.id = SUBQUERY.id)
now i want my regular expression to match following lines only:
select * from Table_A where ID = 90
UNION
select * from Table_B where ID = 90
Please help me, Thank you in advance...
If it is a simple subquery without additional braces, you can just use this regexp
/\(\s*(select[^)]+)\)/i
<?php
$sql = 'Select * from ( select * from Table_A where ID = 90 UNION select * from Table_B where ID = 90 ) as SUBQUERY left join TABL_ABC abc ON (abc.id = SUBQUERY.id)';
if( preg_match('/\(\s*(select.+)\) as /iU', $sql, $matched ) ){
$subquery = trim( $matched[1] );
var_dump( $subquery );
}