CFWheels findAll Group By Having Clause - coldfusion

In CFWheels I am looking at the findAll() page and it has a group by option by doesn't have a Having Clause option. Is there a way to use having clause using findAll() in CFWheels.

Just to share. Credit to Pankaj in the comment for his answer. Thank you
checklist = model("user_checklist").findAll(select="MAX(user_checklist.r_id)", group="r_id HAVING MAX(user_checklist.r_id) > 13");
gives you
SELECT MAX(user_checklist.r_id) FROM user_checklist GROUP BY r_id HAVING MAX(user_checklist.r_id) > 13

It is very disappointing that the dynamic filtering of the grouped data is not available even in the new release CFWheels 1.4.2.
What I found is this issue, it is a very old issue posted under the cfwheels google group and a google group discussion. Even to this day the workaround for using a having in the group by statement is to use the cfrel by dumphreys which is a ColdFusion Relational Algebra Framework.
I would recommend trying it, it is very easy to use and cleanly written. If you navigate to cfrel.cfc you would find a findAll() function which looks similar to the original findAll() in cfwheels (check out the \wheels\model\read.cfm), but there you'll find it supports having() right out of the box.
Example (cfrel having clause):
/*
SQL: SELECT productId, SUM(total) AS totalSum FROM orders
GROUP BY productId HAVING SUM(total) > ?
ORDER BY totalSum DESC LIMIT 5
PARAMS: [1000]
*/
myOrdersRel = relation(datasource="cfrel")
.select("productId,SUM(total) AS totalSum")
.from("orders")
.group("productId")
.having("SUM(total) > ?", [1000])
.order("totalSum DESC")
.limit(5);
query2 = rel2.query();

Related

Datastore GQL: Distinct + Count query

I have a Google Datastore table on this format:
"KEY","Country","PersonName"
"1","USA","Joe"
"2","USA","Dan"
"3","Canada","Willo"
I want to count how many registered people I have on each country. A combination between count aggregation and distinct.
Expected output:
"USA", 2
"Canada", 1
The solution I'm looking for based on GQL.
Thanks for help.
I believe this will require multiple queries.
The first one is to get the list of Countries[1], and then another one to get count for a country[2].
[1] SELECT DISTINCT ON (Country) Country FROM Test
[2] AGGREGATE COUNT(*) OVER (SELECT * FROM Test WHERE Country="USA")
This I believe is due to the Datastore limitations, as mentioned here.
Please note "Test" is my Google Datastore table ("Kind") name here.

How can I remove values from my Parent Grouping?

I would like to categorize questions as yes/no, but i dont want the values to show up on the parent row. Only the users row.
Is it best to setup a hierarchy on one table? Im still new to PowerBI. I want it structured liked the 1st screenshot.
[EXCEL]
[1]: https://i.stack.imgur.com/MztVg.png
[POWERBI]
[2]: https://i.stack.imgur.com/ugAI2.png
You can try with measure. DAX has function HASONEVALUE.
MeasureToTry =
if (hasonevalue(Table[Column]), 1, BLANK() )
Replace 1 depending on your logic.

Birt Report Grouping

I have 2 columns: fltrte_P1_Plt_Per_Id_Fk (Pilot) and fltrte_P2_Plt_Per_Id_Fk (Co-Pilot).
When displaying data in the report I need to group based pilot name. He may be pilot or co-pilot.
It should come in same group. How can this grouping be achieved in a Birt report?
I suggest amending your query from:
select fltrte_P1_Plt_Per_Id_Fk, fltrte_P2_Plt_Per_Id_Fk, ... from flight_Log_Table
to:
select fltrte_P1_Plt_Per_Id_Fk as group_By, ... from flight_Log_Table
union all
select fltrte_P2_Plt_Per_Id_Fk as group_By, ... from flight_Log_Table
then amend your report to group on the new group_By field in the query.
Create a new column that combines the two in your SQL Query.
ISNULL ( fltrte_P1_Plt_Per_Id_Fk, fltrte_P2_Plt_Per_Id_Fk ) as 'Pilot'
If there is a value for P1 (Pilot) it will be in the new field 'Pilot', otherwise P2 (Co-Pilot) will the new field 'Pilot'
This solution works in BIRT 4.2 using a 2008 R2 database.
Add the GROUP BY clause Group by Pilot, Co-Pilot to the end of your SQL query.

FLOW3 Doctrine2 :: SELECT b,count(b) FROM (SELECT a,b FROM x\y\z GROUP BY a) GROUP BY b

I'm quite new to FLOW3 and I'm very new to Doctrine.
I'm just running some tests, and I want to learn or understand some techniques that I'll use later on. Now I'm stuck with this doctrine part where I want to generate some stats.
$results = $this->entityManager
->createQuery('SELECT version,count(version)
FROM (SELECT device, version
FROM \MyStuff\Stats\Domain\Model\Stat
WHERE
date > \'2011-10-01 00:00:00\' and
date < \'2011-10-02 00:00:00\'
GROUP BY device) GROUP BY version')
->getResult();
I asked at other places too, where they directed me to the Doctrine Docs.
Well, now there are several examples but these 2 liners are trivial and I couldn't find any example related to that kind of subselect.
So I hope someone here can help me out.
Edit :
I'd like to solve this using dql.
I tried to solve this using a querybuilder but I was told that querybuilder != dql
Edit 2:
Now I was told that doctrine2 doesn't support subselects in "FROM (SUBSELECT)" but that it does "... WHERE IN (SUBSELECT)" and that one could rewrite my query to the IN () form. Well, trying to figure that out now.
Edit 3:
I'm failing in rewriting the from-subquery into an in-subquery. So... dql doesn't do subqueries and there is no other way to do what I want with dql ?! Then dql would lack a very important feature I'd say. Or am I just not seeing sth. here ?
Edit 4:
I finally got the in-subquery but it was about 10 times slower (4 seconds instead of 0.4) and now I was told by some doctrine guys from #doctrine, that I should use the nativeQuery function instead.
Edit 5:
It works using the nativeQuery now, see my answer for that...
Using a native query it works like that...
$rsm = new \Doctrine\ORM\Query\ResultSetMapping();
$rsm->addScalarResult('version', 'version');
$rsm->addScalarResult('count', 'count');
$results = $this->entityManager
->createNativeQuery(
'SELECT version, COUNT(version) as count FROM
(
SELECT device, version
FROM mystuff_stats_domain_model_stat
WHERE
date > \'2011-10-01 00:00:00\' and
date < \'2011-10-02 00:00:00\'
GROUP BY device
)
as devices GROUP BY version',$rsm)
->execute();
echo var_dump($results,true);

Django: Distinct foreign keys

class Log:
project = ForeignKey(Project)
msg = CharField(...)
date = DateField(...)
I want to select the four most recent Log entries where each Log entry must have a unique project foreign key. I've tries the solutions on google search but none of them works and the django documentation isn't that very good for lookup..
I tried stuff like:
Log.objects.all().distinct('project')[:4]
Log.objects.values('project').distinct()[:4]
Log.objects.values_list('project').distinct('project')[:4]
But this either return nothing or Log entries of the same project..
Any help would be appreciated!
Queries don't work like that - either in Django's ORM or in the underlying SQL. If you want to get unique IDs, you can only query for the ID. So you'll need to do two queries to get the actual Log entries. Something like:
id_list = Log.objects.order_by('-date').values_list('project_id').distinct()[:4]
entries = Log.objects.filter(id__in=id_list)
Actually, you can get the project_ids in SQL. Assuming that you want the unique project ids for the four projects with the latest log entries, the SQL would look like this:
SELECT project_id, max(log.date) as max_date
FROM logs
GROUP BY project_id
ORDER BY max_date DESC LIMIT 4;
Now, you actually want all of the log information. In PostgreSQL 8.4 and later you can use windowing functions, but that doesn't work on other versions/databases, so I'll do it the more complex way:
SELECT logs.*
FROM logs JOIN (
SELECT project_id, max(log.date) as max_date
FROM logs
GROUP BY project_id
ORDER BY max_date DESC LIMIT 4 ) as latest
ON logs.project_id = latest.project_id
AND logs.date = latest.max_date;
Now, if you have access to windowing functions, it's a bit neater (I think anyway), and certainly faster to execute:
SELECT * FROM (
SELECT logs.field1, logs.field2, logs.field3, logs.date
rank() over ( partition by project_id
order by "date" DESC ) as dateorder
FROM logs ) as logsort
WHERE dateorder = 1
ORDER BY logs.date DESC LIMIT 1;
OK, maybe it's not easier to understand, but take my word for it, it runs worlds faster on a large database.
I'm not entirely sure how that translates to object syntax, though, or even if it does. Also, if you wanted to get other project data, you'd need to join against the projects table.
I know this is an old post, but in Django 2.0, I think you could just use:
Log.objects.values('project').distinct().order_by('project')[:4]
You need two querysets. The good thing is it still results in a single trip to the database (though there is a subquery involved).
latest_ids_per_project = Log.objects.values_list(
'project').annotate(latest=Max('date')).order_by(
'-latest').values_list('project')
log_objects = Log.objects.filter(
id__in=latest_ids_per_project[:4]).order_by('-date')
This looks a bit convoluted, but it actually results in a surprisingly compact query:
SELECT "log"."id",
"log"."project_id",
"log"."msg"
"log"."date"
FROM "log"
WHERE "log"."id" IN
(SELECT U0."id"
FROM "log" U0
GROUP BY U0."project_id"
ORDER BY MAX(U0."date") DESC
LIMIT 4)
ORDER BY "log"."date" DESC