How can I change "join with select statement results to" laravel eloquent? - sql

My query like this :
SELECT
*
FROM
(SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1
INNER JOIN
(SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON t1.ks = t2.ks
I want to change it to laravel eloquent. I need to using paginate method from laravel eloquent
I try like this :
$query = \DB::select(\DB::raw("
SELECT *
FROM (
SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
) t1
INNER JOIN (
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks
) t2 ON t1.ks = t2.ks
"));
I'm confused to put paginate method. I need it. Because I want display pagination in view blade laravel
The script like this : {{ $results->appends(Request::query())->render() }}
How can I do it?

Firstly, based on the linked question from which you sourced your database schema, the data you are attempting to query can be found using a far simplier query.
I have written the following query for use on a MySQL DBMS, as neither your, nor the linked question specify a DBMS type.
SELECT ks, COUNT(*) AS tasks, SUM(age < palt) AS late
FROM tasks
GROUP BY ks;
Here's an SQL Fiddle with sample data demonstrating the query works.
Secondly, the aforementioned query can be built using the Laravel query builder as follows.
$results = DB::table('tasks')
->selectRaw('ks, COUNT(*) AS tasks, SUM(age < palt) AS late')
->groupBy('ks')
->paginate(10);

Related

Rewrite query with union in subquery by using gorm

I am trying to write sql query by using gorm. Here the query
SELECT *
FROM (
SELECT unnest(tags) as tag_name FROM models
union all
SELECT unnest(system_tags) from models
left join projects on projects.id = models.project_id
WHERE (projects.is_public = true )) as tD
WHERE LOWER( tD.tag_name ) LIKE '%12%' ORDER BY tag_name
I tried to create subquery. But cant figure out how to add union. As I understand select does not work this way. Is using Raw() my only option?
selectStr := "unnest(tags) as tag_name from models union select unnest(system_tags) from models"
subQuery = db.
Model(&tagsGet).
Select(selectStr).
Joins(joinStrProjects).
Where(whereClause, args...)

SQL Teradata TOP and DISTINCT

I'm trying to write a nested TOP + DISTINCT query in Teradata SQL. My query looks like this:
SELECT TOP 5
*
FROM
(SELECT DISTINCT k_name.KUNDE_NAME1
FROM DB_DWH_MART_AKM_PLT.VW_F_EVENT f_ev
INNER JOIN DBX_DWH_SBX_AKM_PRD.TB_KUNDE_EKP_NAME_AKTUELL k_name ON f_ev.AUFTRAGGEBER_EKP = k_name.EKP
WHERE f_ev.PROCESS_NO = 1075)
I get an error:
Expected something like a name or a Unicode delimited identifier... between ) and ;".
I don't know what I did wrong.
The DISTINCT query would execute correctly on its own.
Why not use a group by?
SELECT TOP 5 k_name.KUNDE_NAME1
FROM DB_DWH_MART_AKM_PLT.VW_F_EVENT f_ev
INNER JOIN DBX_DWH_SBX_AKM_PRD.TB_KUNDE_EKP_NAME_AKTUELL k_name ON f_ev.AUFTRAGGEBER_EKP = k_name.EKP
WHERE f_ev.PROCESS_NO = 1075
GROUP BY k_name.KUNDE_NAME1 --instead of using distinct
ORDER BY k_name.KUNDE_NAME1; --remove or modify as needed

Laravel 4.2 execute query without using elequent query builder

I have a query with sub-query .. and i want to write an explicite SQL request and execute it
Query :
select count(*) as count from
(
SELECT DISTINCT t.article_id FROM
`articles` as a left join `tags` as t
on a.`id` = t.`article_id`
where a.`flag` = 1
) as sub
i tried this to execute the request without building the query :
DB::connection()->getPdo()->exec( $sql );
But it always return 0 !
You can use sub query with DB::raw.
A method DB::raw() (don’t forget to use Illuminate\Support\Facades\DB) allows you to select whatever you want and basically write raw SQL statements.
DB::select(DB::raw("select count(*) as count from
(
SELECT DISTINCT t.article_id FROM
`articles` as a left join `tags` as t
on a.`id` = t.`article_id`
where a.`flag` = 1
) as sub"));
https://laravel.com/docs/4.2/queries#raw-expressions
Why don't you try with DB::raw('your sql query here')
Using DB::select should solve your problem.
DB::select('select count(*) as count from
(
SELECT DISTINCT t.article_id FROM
`articles` as a left join `tags` as t
on a.`id` = t.`article_id`
where a.`flag` = 1
) as sub');

activerecord sql difficult query

I need to make a query with two options: first - select DISTINCT ON, secondly - order by (and order by other fields). BTW, having by don't work
At one sql forum I find a solution
WITH d AS (
SELECT DISTINCT ON ({Dlist}) {slist}
FROM {flist}
....
)
SELECT * FROM d ORDER BY {order fields}
So, how I can make this via ActiveRecord method and get back ActiveRecord::Relation
My full query seems something like that:
WITH d AS (
SELECT DISTINCT ON(item_info_id, volume) items.item_info_id, items.volume, items.*
FROM "items" INNER JOIN "item_info" ON "item_info"."id" = "items"."item_info_id" WHERE "items"."type" IN ('Product')
AND "items"."published" = 't'
AND ("items"."item_info_id" IS NOT NULL)
AND ("items"."price" BETWEEN 2 AND 823489)\
)
SELECT * FROM d ORDER_BY 'price'
Below might work for you or give you some hints
class Item < ActiveRecord::Base
def self.what_you_want_to_achieve
item_ids = where("item_info_id IS NOT NULL")
.select(" DISTINCT on(item_info_id, volume) items.item_info_id, items.volume, items.id ")
.map(&:id)
where(:id => item_ids).published.products.price_between(2,823489).order(:price)
end
I assume you know how to define scope e.g. published

PostgreSQL - how to query "result IN ALL OF"?

I am new to PostgreSQL and I have a problem with the following query:
WITH relevant_einsatz AS (
SELECT einsatz.fahrzeug,einsatz.mannschaft
FROM einsatz
INNER JOIN bergefahrzeug ON einsatz.fahrzeug = bergefahrzeug.id
),
relevant_mannschaften AS (
SELECT DISTINCT relevant_einsatz.mannschaft
FROM relevant_einsatz
WHERE relevant_einsatz.fahrzeug IN (SELECT id FROM bergefahrzeug)
)
SELECT mannschaft.id,mannschaft.rufname,person.id,person.nachname
FROM mannschaft,person,relevant_mannschaften WHERE mannschaft.leiter = person.id AND relevant_mannschaften.mannschaft=mannschaft.id;
This query is working basically - but in "relevant_mannschaften" I am currently selecting each mannschaft, which has been to an relevant_einsatz with at least 1 bergefahrzeug.
Instead of this, I want to select into "relevant_mannschaften" each mannschaft, which has been to an relevant_einsatz WITH EACH from bergefahrzeug.
Does anybody know how to formulate this change?
The information you provide is rather rudimentary. But tuning into my mentalist skills, going out on a limb, I would guess this untangled version of the query does the job much faster:
SELECT m.id, m.rufname, p.id, p.nachname
FROM person p
JOIN mannschaft m ON m.leiter = p.id
JOIN (
SELECT e.mannschaft
FROM einsatz e
JOIN bergefahrzeug b ON b.id = e.fahrzeug -- may be redundant
GROUP BY e.mannschaft
HAVING count(DISTINCT e.fahrzeug)
= (SELECT count(*) FROM bergefahrzeug)
) e ON e.mannschaft = m.id
Explain:
In the subquery e I count how many DISTINCT mountain-vehicles (bergfahrzeug) have been used by a team (mannschaft) in all their deployments (einsatz): count(DISTINCT e.fahrzeug)
If that number matches the count in table bergfahrzeug: (SELECT count(*) FROM bergefahrzeug) - the team qualifies according to your description.
The rest of the query just fetches details from matching rows in mannschaft and person.
You don't need this line at all, if there are no other vehicles in play than bergfahrzeuge:
JOIN bergefahrzeug b ON b.id = e.fahrzeug
Basically, this is a special application of relational division. A lot more on the topic under this related question:
How to filter SQL results in a has-many-through relation
Do not know how to explain it, but here is an example how I solved this problem, just in case somebody has the some question one day.
WITH dfz AS (
SELECT DISTINCT fahrzeug,mannschaft FROM einsatz WHERE einsatz.fahrzeug IN (SELECT id FROM bergefahrzeug)
), abc AS (
SELECT DISTINCT mannschaft FROM dfz
), einsatzmannschaften AS (
SELECT abc.mannschaft FROM abc WHERE (SELECT sum(dfz.fahrzeug) FROM dfz WHERE dfz.mannschaft = abc.mannschaft) = (SELECT sum(bergefahrzeug.id) FROM bergefahrzeug)
)
SELECT mannschaft.id,mannschaft.rufname,person.id,person.nachname
FROM mannschaft,person,einsatzmannschaften WHERE mannschaft.leiter = person.id AND einsatzmannschaften.mannschaft=mannschaft.id;