some order by in doctrine query language - doctrine-orm

I have a query as below :
SELECT t.id, t.name, count(i.id) FROM Acme\TestBundle\Entity\Tags t
LEFT JOIN t.items i WITH i.status=1 AND (SELECT count(img.id) FROM Acme\TestBundle\Entity\ItemsImages img WHERE img.item=i.id) > 0
GROUP BY t.id
ORDER BY COUNT (i.id) DESC
This query works fine without ORDER BY clause. Whenever I add this clause it gives me error :
[Syntax Error] line 0, col 297: Error: Expected end of string, got '('
ORDER BY works with column names but with columns like count(i.id) is not working

To order by an aggregated value, you need to SELECT it first and then use it to ORDER BY:
SELECT
t.id,
t.name,
count(i.id) AS tags_count
FROM
Acme\TestBundle\Entity\Tags t
...
ORDER BY
tags_count DESC

Related

how do i loop through tables to get counts

I have tried to use the following, but it seems that different nodes cannot be mixed:
WITH tables_i_want AS (
SELECT *, table_schema||'.'||table_name as tbl FROM temp.redshift_mod_dates WHERE table_schema = 'whatever'
)
SELECT nspname
FROM pg_catalog.pg_class AS c
JOIN pg_catalog.pg_namespace AS ns
ON c.relnamespace = ns.oid
INNER JOIN tables_i_want as tiw
ON tiw.tbl = c.oid
AND relname not like 'pg_%'
so, then I tried a procedure:
CREATE OR REPLACE PROCEDURE f_test()
LANGUAGE plpgsql
AS $$
DECLARE
full_table_name1 VARCHAR;
full_table_name VARCHAR;
BEGIN
FOR full_table_name IN (SELECT table_schema||'.'||table_name as full_table_name FROM temp.redshift_mod_dates WHERE table_schema = 'whatever')
LOOP
EXECUTE 'SELECT INTO temp.redshift_tables_with_cnt %, COUNT(*) FROM %', full_table_name;
RAISE INFO '%', full_table_name;
END LOOP;
END;
$$;
seems there's an issue with the variable:
[42601] ERROR: syntax error at or near "$1" Where: SQL statement in PL/PgSQL function "f_test" near line 5
If you want to receive the row-count for all the tables you could achieve it using the following query
select tab.table_schema,
tab.table_name,
tinf.tbl_rows as rows
from svv_tables tab
join svv_table_info tinf
on tab.table_schema = tinf.schema
and tab.table_name = tinf.table
where tab.table_type = 'BASE TABLE'
and tab.table_schema not in('pg_catalog','information_schema')
and tinf.tbl_rows > 1
order by tinf.tbl_rows desc;
You can have the data stored into a temporary table and then move them to a persistant table or do further processing as required.

Activeadmin: paginate_collection with group by and sort by alias column name

I am using active-admin to show list of users with following query.
SELECT
agent_id,
COUNT(*) filter (where price BETWEEN 1 AND 200000) as stat_1,
from users
group by agent_id
order by stat_1 desc
LIMIT 20 OFFSET 0
Rails Standard:
User
.select('agent_id, COUNT(*) filter (where price BETWEEN 1 AND 200000) as stat_1').page(params[:page]).per(20)
.group(:agent_id)
.page(params[:page]).per(20)
.order('stat_1 desc')
In ActivAdmin
paginated_collection(users) do
table_for collection, sortable: true do
....
....
end
end
But paginate_collection throws error
PG::UndefinedColumn: ERROR: column "stat_1" does not exist
SELECT COUNT(*) AS count_all, agent_id AS agent_id FROM "users"
GROUP BY "users"."agent_id"
ORDER BY stat_1 desc LIMIT 20 OFFSET 0
How I can resolve this issue?
Its not because of Activeadmin but due to the PostgreSQL.
Actually you are trying to use column alias with ORDER BY clause which PostgreSql will not allow and will always throw an error.The same happens with other clause also when you try to use alias like:
GROUP BY,
Having,
ORDER BY etc
This answer have a good example to do it by defining CASE.
I fixed this issue by changing in paginated_collection.rb line#131 in ActiveAdmin
from
entries_name = I18n.translate key, count: collection.size, default: entry_name.pluralize
to
entries_name = I18n.translate key, count: collection.total_count, default: entry_name.pluralize

Joining 2 results in Doctrine throws error

I am trying to JOIN 2 queries in DQL but I am getting an error which says,
[Semantical Error] line 0, col 114 near '(select u.email': Error: Class '(' is not defined.
I have gone through https://stackoverflow.com/questions/24600439/error-in-nested-subquery-in-dql-class-is-not-defined. But I could not figure out. Please help.
My Query is as follows:
$filterQuery = "SELECT tempResult1.email as email,tempResult1.name as name , tempResult1.id as user
FROM (select u.email as email,a.name as name , u.id as user
FROM
Application\Entity\Userhasrole uhr
INNER JOIN
Application\Entity\Oauthrole r with uhr.applicationrole = r.id
INNER JOIN
Application\Entity\Application a with r.application = a.id
INNER JOIN
Application\Entity\Oauthusers u
) tempResult1
LEFT JOIN
(SELECT uhr1.user as user FROM Application\Entity\Userhasrole uhr1 where
a.id = :applicationId
) tempResult2
with tempResult1.user = tempResult2.user";
$queryObject = $this->getEntityManager()
->createQuery($filterQuery);
$queryObject->setParameter('applicationId', $applicationId);
$result = $queryObject->getResult();
You mix 2 concepts of Doctrine2 :
using SQL
using DQL
If you want to achieve that you want, build tables selections, and not entities selections, you should use EntityManager::createNativeQuery() method and set an SQL query as parameter.
EntityManager::createQuery() is used only for DQL queries

How to count distinct query in Rails 4 with Postgresql?

I have this ActiveRecord query:
Stock.select('DISTINCT ON (stocks.part_number)*').joins(:part, :manufacturer)
.includes(:manufacturer, :part).order(:part_number).with_cat(category).
where(manufacturers: {abbr: ['manufacturer1', 'manufacturer2']})
with_cat is a scope:
scope :with_cat, -> (category) { where(parts: {category_id: category}) }
Now the reason I am using Distinct on is because every manufacturer can have the same part as another, hence duplicates. I do not want duplicates. The above gets the job done. Except when I add count to it I get an error.
PG::SyntaxError: ERROR: syntax error at or near "ON"
LINE 1: SELECT COUNT(DISTINCT ON (stocks.part_number)*) FROM "stocks...
^
: SELECT COUNT(DISTINCT ON (stocks.part_number)*) FROM "stocks"
INNER JOIN "parts" ON "parts"."id" = "stocks"."part_id"
INNER JOIN "manufacturers" ON "manufacturers"."id" = "stocks"."manufacturer_id"
WHERE "parts"."category_id" = 17 AND "manufacturers"."abbr" IN ('manufacturer1', 'manufacturer2')
Not really sure how to add a count to the query without causing that error. I'm not familiar with Distinct on either. Any explanation as to why this is happening would be great!
Does it fix the query if you use the count ahead of distinct? Got the idea per this postgres documentation.
Stock.select('count(distinct part_number)')...

Can JPA join to a codes table when part of join clause requires a hard coded value?

I would like the resulting entity to contain all the columns from table1, plus the description from codes1.
If I were to do this in SQL I would write it as follows:
select table1.*, codes1.description
from table1
inner joing codes1 where codes1.code = table1.status_code
and codes1.group = 'status'
I have done this with a native query, but would like to do this using straight JPA if possible.
Codes Table:
Group Code Description
status a status code a
status b status code b
other a other code a
If we imagine 2 objects: Table1 and Code1.
Your class Table1 contains of course Code1.
In "straight JPA" or jpql you select an object so the query will be:
select t from Table1 t where t.code1.group = 'status'
The join is automaticaly done by the mapping (#OneToOne, #ManyToOne...).