SQL code error mismatched input 'from' expecting - sql

Hi below is my SQL code and it gives me error and I do not know why. If anyone can help.
select time_dif, count(time_dif) as count
from
(
select datediff(so_so_close_time,date_closed) as time_dif
from `mbg_service_prd`.`mds_service_orders_base_cdl`
inner join `mbg_service_prd`.`rnt_incident_detail_base_cdl`
on
(srv_customer_phone = mobile_phone or srv_customer_email = email_address)
where (
(srv_customer_phone<>''or srv_customer_phone is not null)
or (srv_customer_email<>'' or srv_customer_email is not null)
or (mobile_phone<>'' or mobile_phoneis not null)
or (email_addressis<>'' or email_addressis not null)
)
)
group by time_dif
order by time_dif
It gives me error says:
org.apache.spark.sql.catalyst.parser.ParseException:
mismatched input 'from' expecting {, 'WHERE', 'GROUP', 'ORDER', 'HAVING', 'LIMIT', 'LATERAL', 'WINDOW', 'UNION', 'EXCEPT', 'INTERSECT', 'SORT', 'CLUSTER', 'DISTRIBUTE'}(line 3, pos 0)

There is an error in datediff function . We use three parameters in datediff i.e. interval,date1,date2.
DATEDIFF(interval, date1, date2).

Try with the below query
select a.time_dif, count(a.time_dif) as time_dif_count
from
(
select datediff(day,so_so_close_time,date_closed) as time_dif
from mbg_service_prd.mds_service_orders_base_cdl
inner join mbg_service_prd.rnt_incident_detail_base_cdl
on
(srv_customer_phone = mobile_phone or srv_customer_email = email_address)
where (
(srv_customer_phone <> '' or srv_customer_phone is not null)
or (srv_customer_email <> '' or srv_customer_email is not null)
or (mobile_phone <> '' or mobile_phone is not null)
or (email_address <> '' or email_address is not null)
)
)a
group by a.time_dif
order by a.time_dif

Related

How to pass a variable in join query in Laravel

I have a variable that I would like to pass in a joined RAW query. How can I do that ?
$current_user_id = Auth::user()->id;
$query = DB::table('users as u')
->selectRaw('
ROW_NUMBER() OVER (ORDER BY u.id) AS No,
u.id,
u.username,
l.level AS Rank
')
->leftjoin(DB::raw('(
SELECT
u.id as ts_user_id,
u.username as ts_username,
u.email as ts_email,
l.downline_user_id AS ts_downline_user_id ,
outer_u.username AS ts_downline_username,
sum(o.pay_amount) AS ts_team_sales
FROM
users as u
INNER JOIN user_levels AS l
ON l.upline_user_id = u.id
INNER JOIN users as outer_u
ON outer_u.id = l.downline_user_id
LEFT JOIN user_levels as downline_level
ON l.downline_user_id = downline_level.upline_user_id
INNER JOIN users as outerdownline__u
ON outerdownline__u.id = downline_level.downline_user_id
LEFT JOIN orders as o
ON o.user_id = downline_level.downline_user_id
WHERE o.status = 1 AND downline_level.level > 1 AND u.id=1 **//HOW to pass the $current_user_id variable here**
GROUP BY l.downline_user_id
)RESULT_TEAM_SALES') , 'RESULT_TEAM_SALES.ts_downline_user_id' , 'l.downline_user_id')
->where('u.id' , $current_user_id)
->groupBy('l.downline_user_id')
->get()
I would like to replace Where u.id = $current_user_id . Is passing the variable possible ?
Please advise.
Thank you.
Do something like
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.column', '=', $yourVariable);
})
->get();
https://laravel.com/docs/9.x/queries
So, this is how I solved it. I made a sub query
$current_user_id = Auth::user()->id;
$teamSales= DB::table('users as u')
->selectRaw('
u.id,
u.username as ts_username,
l.downline_user_id AS ts_downline_user_id ,
outer_u.username AS ts_downline_username,
sum(o.pay_amount) AS ts_team_sales
')
->join('user_levels as l' , 'u.id' , '=' , 'l.upline_user_id')
->join('users as outer_u' , 'outer_u.id' , '=' , 'l.downline_user_id')
->leftJoin('user_levels as downline_level' , 'l.downline_user_id' , '=' , 'downline_level.upline_user_id')
->leftJoin('orders as o' , 'o.user_id' , '=' , 'downline_level.downline_user_id')
->where('o.status' , '=' , 1)
->where('downline_level.level' , '>' , 1)
->where('u.id' , '=' , $current_user_id)
->groupBy('l.downline_user_id')
;
Then used leftJoinSub method to left join the sub query
$query = DB::table('users as u')
->selectRaw('
ROW_NUMBER() OVER (ORDER BY u.id) AS No,
u.id,
u.username,
team_sales.ts_team_sales
')
->join('user_levels as l' , 'l.upline_user_id' , '=' , 'u.id')
->leftJoinSub($teamSales , 'team_sales' , function($join) {
$join->on('l.downline_user_id', '=', 'team_sales.ts_downline_user_id');
})
->where('u.id' , $current_user_id)
->groupBy('l.downline_user_id')
->get();

postgresql - Aggregate function calls cannot be nested. How can I format this query in a nice json format?

I'm attempting to create a psql query that returns data in a nice json format. Originally for the project we used sequelize and i'm trying to convert it to pure psql. The format i'm looking for is as follows -
...
vehicles:
[
{
services:
[
{
name: "example"
duration: "example"
}
]
id: 1
registration: "example"
}
]
...
Below is what I tried first but got the error. ERROR: aggregate function calls cannot be nested
SELECT
"Bookings"."id",
"Bookings"."startTime",
"Bookings"."code",
"Bookings"."statusId",
"Bookings"."address",
"Bookings"."latitude",
"Bookings"."longitude",
"Bookings"."createdAt",
"Bookings"."overridePrice",
json_build_object(
'fullName', "customer"."fullName",
'id', "customer"."id"
) AS "customer",
json_agg(json_build_object(
'fullName', "serviceProvider"."fullName",
'id', "serviceProvider"."id"
)) AS "serviceProvider",
-- Array of vehicles, this is where the issue lies
json_agg(
json_build_object(
'services', json_agg(
json_build_object(
'name', "ServiceHistories"."name",
'duration', "ServiceHistories"."duration"
)
),
'id', "Vehicles"."id",
'registration', "Vehicles"."registration"
)) AS "vehicles",
-- Everything else works fine
json_agg(
json_build_object(
'amount', "payments"."amount",
'amountFromGiftCard', "payments"."amountFromGiftCard"
)
) AS "payments"
FROM
"Bookings",
"Users" AS "customer",
"Users" AS "serviceProvider",
"BookingServiceProviders",
"BookingVehicleServices",
"BookingVehicles",
"Vehicles",
"Payments" AS "payments",
"ServiceHistories"
WHERE
"Bookings"."isDeleted" IS NOT true AND
"Bookings"."statusId" != 4 AND
"Bookings"."customerId" = "customer"."id" AND "customer"."userTypeId" = 1 AND
"Bookings"."id" = "BookingServiceProviders"."BookingId" AND
"BookingServiceProviders"."UserId" = "serviceProvider"."id" AND
"Bookings"."id" = "BookingVehicles"."BookingId" AND
"Vehicles"."id" = "BookingVehicles"."VehicleId" AND
"Bookings"."id" = "payments"."bookingId" AND
"BookingVehicles"."id" = "BookingVehicleServices"."BookingVehicleId" AND
"ServiceHistories"."bookingId" = "Bookings"."id"
GROUP BY
"Bookings"."id",
"customer"."id",
"customer"."fullName"
Order by "startTime" ASC
After doing some googling I found that i'll probably have to do a sub query for the services array. Below is what I attempted but the query runs indefinitely.
SELECT
"Bookings"."id",
"Bookings"."startTime",
"Bookings"."code",
"Bookings"."statusId",
"Bookings"."address",
"Bookings"."latitude",
"Bookings"."longitude",
"Bookings"."createdAt",
"Bookings"."overridePrice",
json_build_object(
'fullName', "customer"."fullName",
'id', "customer"."id"
) AS "customer",
json_agg(json_build_object(
'fullName', "serviceProvider"."fullName",
'id', "serviceProvider"."id"
)) AS "serviceProvider",
-- Issue lies here
json_agg(
json_build_object(
'services', (
SELECT
json_agg(json_build_object(
'name', "ServiceHistories"."name",
'duration', "ServiceHistories"."duration"
))
FROM
"ServiceHistories"
WHERE
"ServiceHistories"."bookingId" = "Bookings"."id"
),
'id', "Vehicles"."id",
'registration', "Vehicles"."registration"
)) AS "vehicles",
-- End of issue
json_agg(
json_build_object(
'amount', "payments"."amount",
'amountFromGiftCard', "payments"."amountFromGiftCard"
)
) AS "payments"
FROM
"Bookings",
"Users" AS "customer",
"Users" AS "serviceProvider",
"BookingServiceProviders",
"BookingVehicleServices",
"BookingVehicles",
"Vehicles",
"Payments" AS "payments"
WHERE
"Bookings"."isDeleted" IS NOT true AND
"Bookings"."statusId" != 4 AND
"Bookings"."customerId" = "customer"."id" AND "customer"."userTypeId" = 1 AND
"Bookings"."id" = "BookingServiceProviders"."BookingId" AND
"BookingServiceProviders"."UserId" = "serviceProvider"."id" AND
"Bookings"."id" = "BookingVehicles"."BookingId" AND
"Vehicles"."id" = "BookingVehicles"."VehicleId" AND
"Bookings"."id" = "payments"."bookingId" AND
"BookingVehicles"."id" = "BookingVehicleServices"."BookingVehicleId"
GROUP BY
"Bookings"."id",
"customer"."id",
"customer"."fullName"
Order by "startTime" ASC
If anyone could help or point me in the right direction I'd appreciate it.
** EDIT **
I kind of have it working by adding more where clauses on how the tables relate, now the services are returning correctly within the vehicles array. Sadly its super slow. I had it working faster but there were duplicate services when it should have only been ones related to the specific booking.
SELECT
bookings."id",
bookings."startTime",
bookings."code",
bookings."statusId",
bookings."address",
bookings."latitude",
bookings."longitude",
bookings."createdAt",
bookings."overridePrice",
json_build_object(
'fullName', "customer"."fullName",
'id', "customer"."id"
) AS "customer",
json_agg(json_build_object(
'fullName', "serviceProvider"."fullName",
'id', "serviceProvider"."id"
)) AS "serviceProvider",
json_agg(
json_build_object(
'amount', "payments"."amount",
'amountFromGiftCard', "payments"."amountFromGiftCard"
)
) AS "payments",
(
SELECT
(nested_vehicles)
FROM (
SELECT
"Vehicles".id as vehicle_id,
"Vehicles".registration,
(
SELECT
json_agg(nested_services)
FROM (
SELECT
"ServiceHistories"."id",
"ServiceHistories"."name",
"ServiceHistories"."duration"
FROM
"ServiceHistories", "BookingVehicleServices", "BookingVehicles"
WHERE
"ServiceHistories"."vehicleId" = "Vehicles"."id" AND
"ServiceHistories"."id" = "BookingVehicleServices"."ServiceHistoryId" AND
bookings.id = "BookingVehicles"."BookingId" AND
"Vehicles"."id" = "BookingVehicles"."VehicleId" AND
"ServiceHistories"."bookingId" = bookings.id
) AS nested_services
) AS services
FROM
"Vehicles", "BookingVehicles"
WHERE "Vehicles"."id" = "BookingVehicles"."VehicleId" AND bookings.id = "BookingVehicles"."BookingId"
GROUP BY "Vehicles"."id"
) AS nested_vehicles
) AS vehicles
FROM
"Bookings" as bookings,
"Users" AS "customer",
"Users" AS "serviceProvider",
"BookingServiceProviders",
"Payments" AS "payments"
WHERE
bookings."isDeleted" IS NOT true AND
bookings."statusId" != 4 AND
bookings."customerId" = "customer"."id" AND "customer"."userTypeId" = 1 AND
bookings."id" = "BookingServiceProviders"."BookingId" AND
"BookingServiceProviders"."UserId" = "serviceProvider"."id" AND
bookings."id" = "payments"."bookingId"
GROUP BY
bookings."id",
"customer"."id",
"customer"."fullName"
Order by "startTime" ASC
Not really sure what to do here. I might just return the services separate and then format them externally :/
ERROR: aggregate function calls cannot be nested
Not sure for best practice but I use subqueries or Common Table Expressions (CTE).
First aggregate function call makes from subquery/CTE, second aggregate function call makes from query.
-- Common Table Expressions
WITH regional_sales AS (
SELECT region, SUM(amount) AS total_sales
FROM orders
GROUP BY region
), top_regions AS (
SELECT region
FROM regional_sales
WHERE total_sales > (SELECT SUM(total_sales)/10 FROM regional_sales)
)
SELECT region,
product,
SUM(quantity) AS product_units,
SUM(amount) AS product_sales
FROM orders
WHERE region IN (SELECT region FROM top_regions)
GROUP BY region, product;

error: syntax error at or near "S" node posgres

My question is I can't resolve the error 42601 which is I know that a syntax error. I run the query on pgadmin and it just works fine. Here's my code
I need to concatenate process of query to solve different requests of user.
ps. im using node posgres promise
return new Promise((resolve,reject)=>{
let {searchType , searchValue , sortType , filterType , size , index} = req.params;
var select_clause = `SELECT svn_id , mobile_number , network_prefixes.prefix , network_prefixes.country_name , date_created ,
date_subscribed , expiry_date , svn_status ,
(select count(*) from svn_transactions where svn_status = 'ACTIVE') "total_active_svn",
(select count(*) from svn where status = 'UNASSIGNED') "total_available_svn",
(select count(*) from svn_transactions where (svn_status = 'INACTIVE' OR svn_status = 'INCOMING_SMS_ONLY')) "total_grace_svn"
FROM svn_transactions
LEFT JOIN network_prefixes ON network_prefixes.prefix = substr(svn_transactions.mobile_number,1,length(network_prefixes.prefix)) `;
var where_clause;
switch(searchType){
case 'MOBILE_NUMBER':
where_clause = `WHERE (mobile_number LIKE '%' || $1 || '%') `;
break;
case 'SVN_NUMBER':
where_clause = `WHERE (svn_id LIKE '%' || $1 || '%') `;
break;
default: //ALL
where_clause = `WHERE (mobile_number LIKE '%' || $1 || '%') OR (svn_id LIKE '%' || $1 || '%') `;
}
var sort_type;
switch(sortType){
case 'MOBILE_NUMBER':
sort_type = `order by mobile_number `;
break;
case 'SVN_NUMBER':
sort_type = `order by svn_id `;
break;
case 'RENEWAL_DATE':
sort_type = `order by date_subscribed `;
break;
case 'SUBSCRIPTION_DATE':
sort_type = `order by date_created `;
break;
}
var pagination = ` limit $2 offset $3`;
var query = `${select_clause} ${where_clause} ${sort_type} ${filterType} ${pagination}`;
pool.query(query[
searchValue , size , index
],function(err,result){
if(err) {
console.log(err);
reject(err);
}resolve(result);
});
});
response error is:
error: syntax error at or near "S"
at Connection.parseE (/var/www/appvno/admin/node_modules/pg/lib/connection.js:614:13)
at Connection.parseMessage (/var/www/appvno/admin/node_modules/pg/lib/connection.js:413:19)
at Socket.<anonymous> (/var/www/appvno/admin/node_modules/pg/lib/connection.js:129:22)
at Socket.emit (events.js:315:20)
at addChunk (_stream_readable.js:295:12)
at readableAddChunk (_stream_readable.js:271:9)
at Socket.Readable.push (_stream_readable.js:212:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23) {
length: 89,
severity: 'ERROR',
code: '42601',
detail: undefined,
hint: undefined,
position: '1',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'scan.l',
line: '1134',
routine: 'scanner_yyerror'}
I tried just combining them into 1 single query and it just works fine.:
var example_query = `SELECT svn_id , mobile_number , network_prefixes.prefix , network_prefixes.country_name ,
date_created , date_subscribed , expiry_date , svn_status ,
(select count(*) from svn_transactions where svn_status = 'ACTIVE') "total_active_svn",
(select count(*) from svn where status = 'UNASSIGNED') "total_available_svn",
-- total_recycled_svn
(select count(*) from svn_transactions where (svn_status = 'INACTIVE' OR svn_status = 'INCOMING_SMS_ONLY')) "total_grace_svn"
FROM svn_transactions
left join network_prefixes on network_prefixes.prefix = substr(svn_transactions.mobile_number,1,length(prefix))
WHERE (mobile_number LIKE '%' || $1 || '%')
order by mobile_number DESC
limit $2 offset $3`;
I researched if its theres a limitation on concatenation of select query but I found nothing. Any help will do, thanks!
EDIT 1: I already checked if spaces are correct and also no missing semicolons... based on 42601 meaning
EDIT 2: Here's my console.log of concatenated query"
SELECT svn_id , mobile_number , network_prefixes.prefix , network_prefixes.country_name , date_created ,
date_subscribed , expiry_date , svn_status ,
(select count(*) from svn_transactions where svn_status = 'ACTIVE') "total_active_svn",
(select count(*) from svn where status = 'UNASSIGNED') "total_available_svn",
(select count(*) from svn_transactions where (svn_status = 'INACTIVE' OR svn_status = 'INCOMING_SMS_ONLY')) "total_grace_svn"
FROM svn_transactions
LEFT JOIN network_prefixes ON network_prefixes.prefix = substr(svn_transactions.mobile_number,1,length(network_prefixes.prefix)) WHERE (mobile_number LIKE '%' || $1 || '%') order by mobile_number DESC limit $2 offset $3
Still works fine on pgadmin but still error 42601 on node postgres
At this part:
`SELECT svn_id , mobile_number , network_prefixes.prefix , network_prefixes.country_name ,
date_created , date_subscribed , expiry_date , svn_status ,
(select count(*) from svn_transactions where svn_status = 'ACTIVE'
use \ ' instead of ' at 'ACTIVE' (no spaces between \ and ')
Also, why are you using ` to delimit a string? Shouldn't it be ' ?
I found the error. It's not the query but the error was my setup of pool.query. I just forget adding comma after the query and before the values. hehe stupid me
before: pool.query(query[..
after: pool.query(query,[..

Why return 4 value when want just 1 for my query?

I have this query for get a value from a table:
SELECT
AssemblySite, AssemblyPlannedDate, AssemblyDate,
ShippmentPlannedDate, ShippmentDate, DelayMotive,
LogisticsResponsable, HasBOM, HasSerialComponents,
PrototypeComponents, ReadyForAssembly, OrderPriority, DeliveryTime,
RequesterApproval, ApprovedDate, PlannedFinishYear, PlannedFinishWeek,
Designer, RawMaterial, SpecialMaterial, TestArea, DesignHours,
Temperature, TestType
FROM
Orders_Header
WHERE
(DVMOrderNumber = '%15078702%')
AND (Status = 'Completely Defined')
OR (Status = 'Assembly')
OR (Status = 'Post-Assembly')
OR (Status = 'Document review')
OR (Status = 'Delivery approval')
OR (Status = 'Shipping')
ORDER BY
AssemblyPlannedDate
I have column DVMOrderNumer and I want a value, more specific is this: SO-15078702. But when I search my value with this query return 4 value.
More specific:
SO-15078702, SO-15078703, SO-15078704, SO-15073792-08
Where am I going wrong? I want to get just one value from my table. The DVMOrderNumber has more stats like Assembly, Post-Assembly...
Your query will be executed in following order
((DVMOrderNumber = '%15078702%') AND (Status = 'Completely Defined')) OR
((Status = 'Assembly') OR
(Status = 'Post-Assembly') OR
(Status = 'Document review') OR
(Status = 'Delivery approval') OR
(Status = 'Shipping'))
You need to use proper Parenthesis to filter properly. Try this where clause
WHERE ( DVMOrderNumber Like '%15078702%' )
AND ( ( Status = 'Completely Defined' )
OR ( Status = 'Assembly' )
OR ( Status = 'Post-Assembly' )
OR ( Status = 'Document review' )
OR ( Status = 'Delivery approval' )
OR ( Status = 'Shipping' ) )
OR Use IN
WHERE ( DVMOrderNumber Like '%15078702%' )
AND Status IN ( 'Completely Defined', 'Assembly', 'Post-Assembly', 'Document review',
'Delivery approval', 'Shipping' )
You query is probably not being parsed the way you want. So, learn to use IN:
WHERE DVMOrderNumber like '%15078702%' AND
Status IN ('Completely Defined', 'Assembly', 'Post-Assembly', 'Document review', 'Delivery approval', 'Shipping')
Your original query is parsed as:
WHERE (DVMOrderNumber like '%15078702%' AND Status = 'Completely Defined') OR
(status = 'Assembly' OR
. . .
)
That is, the status is only tied to the order number for the first comparison. You could, of course, fix your original query using parentheses, but IN is a cleaner method.

Zend select object - building a query

How can I write the query below in Zend Select object notation so using ->join()->where() etc?
SELECT t.id, t.user_id, t.added_date, u.id, u.phone, bk.call_status
FROM `transaction` t
INNER JOIN
(
SELECT id, MAX(added_date) AS addedDate
FROM `transaction`
GROUP BY id
) gt
ON t.id = gt.id AND t.added_date = gt.addedDate
LEFT JOIN `user` u ON t.user_id = u.id
LEFT JOIN `bok_call` bk ON bk.user_id = t.user_id
WHERE NOT t.user_id = 'null'
AND addedDate BETWEEN '2008-05-04 17:51:48' AND '2009-05-04 17:51:48'
AND NOT u.phone = ''
AND bk.call_status IS null
For example this way:
$joinSelect = $model->select()
->from('transaction'), array('id', 'addedDate' => 'MAX(added_date)'))
->group('id');
$select = $model->select()
->setIntegrityCheck(false)
->from(array('t' => 'transaction'), array('id', 'user_id', 'added_date'))
->join(array('gt' => $joinSelect), 't.id = gr.id AND t.added_date = gt.addedDate', array());
->joinLeft(array('u' => 'user'), 't.user_id = u.id', array('id', 'phone'))
->joinLeft(array('bk' => 'bok_call'), 'bk.user_id = t.user_id', array('call_status'))
->where('t.user_id != ?', 'null')
->where("addedDate BETWEEN '2008-05-04 17:51:48' AND '2009-05-04 17:51:48')
->where('u.phone != ?', '')
->where('bk.call_status IS NULL');
Be aware that you won't be able to differentiate 't.id' and 'u.id' in result.