How to make this query in laravel? - laravel

I'm trying to make a query in Laravel, but it's not working. I USE POSTGRESQL
select extract(year from fecha_creacion) as anio, extract(month from fecha_creacion) as mes,
sum(case when tipo = 'entrada' then 1 else 0 end )
from documento
group by extract(year from fecha_creacion), extract(month from fecha_creacion)
order by anio, mes;
I also tried the following.
$data = DB::table('documento')
->selectRaw('year from fecha_creacion AS anio, month from fecha_creacion AS mes')
->sum(case when tipo = 'entrada' then 1 else 0 end )
->orderBy(anio, mes, DESC)
->get();

You can use laravel DB::raw() expresssion query.
You have to pass the query in raw function.
reference: https://laravel.com/docs/5.8/queries#raw-expressions

Related

Adding filters in subquery from CTE quadruples run time

I am working on an existing query for SSRS report that focuses on aggregated financial aid data split out into 10 aggregations. User wants to be able to select students included in that aggregated data based on new vs. returning and 'selected for verification.' For the new/returning status, I added a CTE to return the earliest admit date for a student. 2 of the 10 data fields are created by a subquery. I have been trying for 3 days to get the subquery to use the CTE fields for a filter, but they won't work. Either they're ignored or I get a 'not a group by expression' error. If I put the join to the CTE within the subquery, the query time jumps from 45 second to 400 seconds. This shouldn't be that complicated! What am I missing? I have added some of the code... 3 of the chunks work - paid_something doesn't.
with stuStatus as
(select
person_uid, min(year_admitted) admit_year
from academic_study
where aid_year between :AidYearStartParameter and :AidYearEndParameter
group by person_uid)
--- above code added to get student information not originally in qry
select
finaid_applicant_status.aid_year
, count(1) as fafsa_cnt --works
, sum( --works
case
when (
package_complete_date is not null
and admit.status is not null
)
then 1
else 0
end
) as admit_and_package
, (select count(*) --does't work
from (
select distinct award_by_aid_year.person_uid
from
award_by_aid_year
where
award_by_aid_year.aid_year = finaid_applicant_status.aid_year
and award_by_aid_year.total_paid_amount > 0 )dta
where
(
(:StudentStatusParameter = 'N' and stuStatus.admit_year = finaid_applicant_status.aid_year)
OR
(:StudentStatusParameter = 'R' and stuStatus.admit_year <> finaid_applicant_status.aid_year)
OR :StudentStatusParameter = '%'
)
)
as paid_something
, sum( --works
case
when exists (
select
1
from
award_by_person abp
where
abp.person_uid = fafsa.person_uid
and abp.aid_year = fafsa.aid_year
and abp.award_paid_amount > 0
) and fafsa.requirement is not null
then 1
else 0
end
) as paid_something_fafsa
from
finaid_applicant_status
join finaid_tracking_requirement fafsa
on finaid_applicant_status.person_uid = fafsa.person_uid
and finaid_applicant_status.aid_year = fafsa.aid_year
and fafsa.requirement = 'FAFSA'
left join finaid_tracking_requirement admit
on finaid_applicant_status.person_uid = admit.person_uid
and finaid_applicant_status.aid_year = admit.aid_year
and admit.requirement = 'ADMIT'
and admit.status in ('M', 'P')
left outer join stuStatus
on finaid_applicant_status.person_uid = stuStatus.person_uid
where
finaid_applicant_status.aid_year between :AidYearStartParameter and :AidYearEndParameter
and (
(:VerifiedParameter = '%') OR
(:VerifiedParameter <> '%' AND finaid_applicant_status.verification_required_ind = :VerifiedParameter)
)
and
(
(:StudentStatusParameter = 'N' and (stuStatus.admit_year IS NULL OR stuStatus.admit_year = finaid_applicant_status.aid_year ))
OR
(:StudentStatusParameter = 'R' and stuStatus.admit_year <> finaid_applicant_status.aid_year)
OR :StudentStatusParameter = '%'
)
group by
finaid_applicant_status.aid_year
order by
finaid_applicant_status.aid_year
Not sure if this helps, but you have something like this:
select aid_year, count(1) c1,
(select count(1)
from (select distinct person_uid
from award_by_aid_year a
where a.aid_year = fas.aid_year))
from finaid_applicant_status fas
group by aid_year;
This query throws ORA-00904 FAS.AID_YEAR invalid identifier. It is because fas.aid_year is nested too deep in subquery.
If you are able to modify your subquery from select count(1) from (select distinct sth from ... where year = fas.year) to select count(distinct sth) from ... where year = fas.year then it has the chance to work.
select aid_year, count(1) c1,
(select count(distinct person_uid)
from award_by_aid_year a
where a.aid_year = fas.aid_year) c2
from finaid_applicant_status fas
group by aid_year
Here is simplified demo showing non-working and working queries. Of course your query is much more complicated, but this is something what you could check.
Also maybe you can use dbfiddle or sqlfiddle to set up some test case? Or show us sample (anonimized) data and required output for them?

Oracle script for getting results and update a table column in the same time

I would like your help for creating a script for getting results and in the same time updating a field in my table if necessary.
In my application, I have persons (table PERSON) who create REQUESTS (table REQUEST). A person is active when she has created a request during the last 3 years. I have created a field (ACTIVE - default value: 1) in the table PERSON in order to know if the person is still active.
I create a query for retrieving the number of requests for each person (Total request number, active request, inactive request):
-- PERSONS List with number of request for each person and RE_ACTIVE field
SELECT p.id,
p.lastname || ' ' || p.firstname personname,
p.company,
p.active,
(SELECT count(*)
FROM request req
WHERE req.personid = p.id) total_request_nb,
(SELECT count(*)
FROM request reqact
WHERE reqact.personid = p.id
AND reqact.requestdate > add_months(trunc(sysdate, 'YYYY'), -36)) nb_active_requests,
(SELECT count(*)
FROM request reqinact
WHERE reqinact.personid = p.id
AND reqinact.requestdate < add_months(trunc(sysdate, 'YYYY'), -36)) nb_inactive_requests,
CASE
WHEN EXISTS (SELECT *
FROM request reqreact
WHERE reqreact.personid = p.id
AND reqreact.requestdate > add_months(trunc(sysdate, 'YYYY'), -36))
THEN 1
ELSE 0
END re_active
FROM person p;
This script is working. I would like to update the field ACTIVE when the person is active (with the previous result). For instance:
UPDATE PERSON p SET ACTIVE =
CASE WHEN (
(SELECT count(*)
FROM request reqreact
WHERE reqreact.personid = p.id
AND reqreact.requestdate > add_months(trunc(sysdate, 'YYYY'), -36)) > 0
)
THEN 1
ELSE 0
END
I would like to know if it's possible to do that in the same script? Hence I could know how many updates have been done, failed, ... in once query.
Thanks you in advance for your help
You want a WHERE EXISTS condition with a correlated subquery :
UPDATE PERSON p
SET p.ACTIVE = 1
WHERE EXISTS (
SELECT 1
FROM request reqreact
WHERE reqreact.personid = p.id
AND reqreact.requestdate > add_months(trunc(sysdate, 'YYYY'), -36)
)
If there is no match in the subquery, the UPDATE in the outer query will not happen.
If you want to set to 1 or 0 depending on the result of the subquery :
UPDATE PERSON p
SET p.ACTIVE = CASE
CASE
WHEN EXISTS (
SELECT 1
FROM request reqreact
WHERE reqreact.personid = p.id
AND reqreact.requestdate > add_months(trunc(sysdate, 'YYYY'), -36)
)
THEN 1
ELSE 0
END

how to extract the year from a date in Oracle?

I dont understand why the following query does not work
SELECT stringdate, TO_DATE(TO_CHAR(stringdate),'YYYYMMDD') AS mydate,
EXTRACT(YEAR FROM MYDATE) as myyear
FROM data.repo data
WHERE ROWNUM <10"
It returns ORA-00904: "MYDATE": invalid identifier
However, just running
SELECT stringdate, TO_DATE(TO_CHAR(stringdate),'YYYYMMDD') AS mydate
gives correctly:
stringdate MYDATE
20150130 2015-01-30
This drives me crazy. What is the issue? Thanks!
The problem is that you CANNOT reference the alias "mydate" in the same select clause.
SELECT
stringdate
, EXTRACT(YEAR FROM MYDATE) as myyear
FROM (
SELECT stringdate
, TO_DATE(TO_CHAR(stringdate),'YYYYMMDD') AS mydate
FROM data.repo data
WHERE ROWNUM <10
)
There are other possibilities e.g.
SELECT stringdate
, TO_DATE(TO_CHAR(stringdate),'YYYYMMDD') AS mydate
, to_number(substr(stringdate,1,4)) AS YR
FROM data.repo data
WHERE ROWNUM <10
for use of "select *" (nb: not recommend in production coding) in Oracle you need o use the table/subquery aliases, like so:
SELECT
d.*
, EXTRACT(YEAR FROM MYDATE) as myyear
FROM (
SELECT data.*
, TO_DATE(TO_CHAR(stringdate),'YYYYMMDD') AS mydate
FROM data.repo data
WHERE ROWNUM <10
) d
Select mydate, EXTRACT(YEAR FROM MYDATE) as myyear
From (
SELECT stringdate, TO_DATE(TO_CHAR(stringdate),'YYYYMMDD') AS mydate
/* , EXTRACT(YEAR FROM MYDATE) as myyear */
FROM data.repo data
WHERE ROWNUM <10"
) A

Issue with Case and Extract Function

I am writing a SELECT Query as below
SELECT COUNT(*) AS Number_of_rows
FROM PAY_DETL
WHERE
CASE
WHEN
Extract(MONTH FROM CURRENT_DATE) > 9
THEN
Extract(YEAR FROM PAY_EVT_BGN_DT) = Extract(YEAR FROM CURRENT_DATE) AND Extract(MONTH FROM CURRENT_DATE) > 9;
Where i am getting below error
ORA-00905: missing keyword
00905. 00000 - "missing keyword
statement where i am getting error is Extract(YEAR FROM PAY_EVT_BGN_DT "here")
Could someone please help me with above?
Thanks
A query nor a comment you posted help much; what does "not assign" mean?
Anyway: you can't use a conditional WHERE clause that way. A simple option is to split the query into two parts and UNION them, having the "distinguishing" parts of the WHERE clause opposite.
For example:
select count(*) as number_of_rows
from pay_detl
where extract(year from pay_evt_bgn_dt) = extract(year from current_date)
and extract(month from current_date) > 9 --> this condition ...
union
select count(*) as number_of_rows
from pay_detl
where condition_different_from_the_one_above
and extract(month from current_date) <= 9 --> ... is just the opposite from this one
If it doesn't help, please, modify the question, provide test case so that we'd see the input and describe what would the output look like (based on that input).
We must differentiate the two main conditions <,> 9. Then, there is to account for each case:
SELECT SUM(CASE WHEN Extract(MONTH FROM SYSDATE) > 9 THEN
DECODE(Extract(YEAR FROM PAY_EVT_BGN_DT), Extract(YEAR FROM CURRENT_DATE), 1, 0)
END COUNT_MORE_NINE),
SUM(CASE WHEN Extract(MONTH FROM SYSDATE) <= 9 THEN
1
END COUNT_ANOTHER)
FROM PAY_DETL;

Please teach me how to laravel-querybuilder left join

select t2.id,name,count(*) as toroku ,
sum(case when tion_flg <> 0 THEN 1 ELSE 0 END ) as riyou,t2.upload_at
FROM id_master as t1
LEFT JOIN id_upload as t2
ON t1.upload_id = t2.upload_id
GROUP BY t2.id,t2.name,t2.upload_at
ORDER BY id
I' d like to make laravel query.
Try this
DB::table('id_master AS t1')
->select(DB::raw('
t2.id,
name,
count(*) AS toroku,
SUM(CASE WHEN tion_flg <> 0 THEN 1 ELSE 0 END ) AS riyou,
t2.upload_at'))
->leftJoin('id_upload AS t2', 't1.upload_id', '=', 't2.upload_id')
->groupBy('t2.id','t2.name','t2.upload_at')
->orderBy('id')
->get();

Resources