Can't access column pick_country_iso - mysql

I have this query
SELECT pick_up_id, (select pick_name from pick_up_point where pick_up_point.pick_up_id = s.pick_up_id limit 1) as pick_name, total_boxes, (SUM(r_occupied) + SUM(s_occupied)) AS total_occupied, (total_boxes - (SUM(r_occupied) + SUM(s_occupied))) as free_boxes, round(((SUM(r_occupied) + SUM(s_occupied)) / total_boxes * 100),2) as pct_usage,(select pick_country_iso from pick_up_point where pick_up_point.pick_up_id = s.pick_up_id limit 1) as pick_country_iso
FROM(
SELECT p.r_pick_up_id AS pick_up_id, COUNT(p.parcel_id) AS r_occupied, 0 AS s_occupied,
(SELECT COUNT(rl.lookup_id) FROM racks r INNER JOIN rack_lookup rl ON rl.rack_type = r.rack_type WHERE r.pick_up_id = p.r_pick_up_id) AS total_boxes
FROM v_last_parcel_event p
WHERE p.event_type IN (2,3,6,8,16,18,26,27,101,102,104,105,107,112,122,124,127,151,152,153)
AND p.box_size <= 3 AND IFNULL(p.overflow_parcel, 0) = 0
AND p.r_pick_up_id IS NOT NULL
GROUP BY p.r_pick_up_id
UNION ALL
SELECT p.s_pick_up_id AS pick_up_id, 0 AS r_occupied, COUNT(p.parcel_id) AS s_occupied,
(SELECT COUNT(rl.lookup_id) FROM racks r INNER JOIN rack_lookup rl ON rl.rack_type = r.rack_type WHERE r.pick_up_id = p.s_pick_up_id) AS total_boxes
FROM v_last_parcel_event p
WHERE p.event_type IN (2,6,8,12,16,18,26,27,101,102,104,105,107,112,122,124,151,152,153)
AND p.box_size <= 3 AND IFNULL(p.overflow_parcel, 0) = 0
AND p.s_pick_up_id IS NOT NULL
GROUP BY p.s_pick_up_id
) as s
GROUP BY s.pick_up_id;
On above query on first line, i'm getting column pick_country_iso
(select pick_country_iso from pick_up_point where pick_up_point.pick_up_id = s.pick_up_id limit 1) as pick_country_iso
The result is in following image.
Now i'm trying to add a where clause in the above query at the end
as s WHERE pick_country_iso="ABC"
GROUP BY s.pick_up_id;
but I'm getting this error #1054 - Unknown column 'pick_country_iso' in 'where clause'.
Thank you for any help.

Related

Why integer cast is not working with integer group_concat() list?

I'm stuck at the query where I need to concat IDs of the table. And from that group of IDs, I need to fetch that rows in sub query. But when I try to do so, MySQL consider group_concat() as a string. So that condition becomes false.
select count(*)
from rides r
where r.ride_status = 'cancelled'
and r.id IN (group_concat(rides.id))
*************** Original Query Below **************
-- Daily Earnings for 7 days [Final]
select
group_concat(rides.id) as ids,
group_concat(ride_category.name) as rideType,
group_concat(ride_cars.amount + ride_cars.commission) as rideAmount ,
group_concat(ride_types.name) as carType,
count(*) as numberOfRides,
(
select count(*) from rides r where r.ride_status = 'cancelled' and r.id IN (group_concat(rides.id) )
) as cancelledRides,
(
select count(*) from rides r where r.`ride_status` = 'completed' and r.id IN (group_concat(rides.id))
) as completedRides,
group_concat(ride_cars.status) as status,
sum(ride_cars.commission) + sum(ride_cars.amount) as amount,
date_format(from_unixtime(rides.requested_at/1000 + rides.offset*60), '%Y-%m-%d') as requestedDate,
date_format(from_unixtime(rides.requested_at/1000 + rides.offset*60), '%V') as week
from
ride_cars,
rides,
ride_category,
ride_type_cars,
ride_types
where
ride_cars.user_id = 166
AND (rides.ride_status = 'completed' or. rides.ride_status = 'cancelled')
AND ride_cars.ride_id = rides.id
AND (rides.requested_at >= 1559347200000 AND requested_at < 1561852800000)
AND rides.ride_category = ride_category.id
AND ride_cars.car_model_id = ride_type_cars.car_model_id
AND ride_cars.ride_type_id = ride_types.id
group by
requestedDate;
Any solutions will be appreciated.
Try to replace the sub-query
(select count(*) from rides r where r.ride_status = 'cancelled' and r.id IN (group_concat(rides.id) )) as cancelledRides,
with below to count using SUM and CASE, it will make use of the GROUP BY
SUM(CASE WHEN rides.ride_status = 'cancelled' THEN 1 ELSE 0 END) as cancelledRides
and the same for completedRides
And move to using JOIN instead of implicit joins

Sql server errors in query

I am trying to collaborate 3 queries to perform arithmetic operation. The queries are shown in
(SELECT ITEM_ID,ISNULL(SUM(REC_GOOD_QTY),0)
FROM INVENTORY_ITEM
WHERE COMPANY_ID = 1
AND INVENTORY_ITEM.COMPANY_BRANCH_ID = 1
AND INVENTORY_ITEM.INV_ITEM_STATUS = 'Inward'
AND GRN_DATE < CAST('2017-01-10 00:00:00.0' AS DATETIME)
GROUP BY INVENTORY_ITEM.ITEM_ID) -
(SELECT ITEM_ID, SUM ( TOTAL_LITRE )
FROM STOCK_REQUISITION_ITEM B, STOCK_REQUISITION A
WHERE A.ID = B.REQUISITION_ID
AND A.COMPANY_ID = 1
AND A.REQ_FROM_BRANCH_ID = 1
AND A.REQUISITION_DATE < CAST('2017-01-10 00:00:00.0' AS DATETIME)
GROUP BY B.ITEM_ID) +
(SELECT ITEM_ID, SUM ( RETURN_QUANTITY )
FROM STOCK_RETURN_ITEM B, STOCK_RETURN A
WHERE A.ID = B.STOCK_RETURN_ID
AND A.COMPANY_ID = 1
AND A.COMPANY_BRANCH_ID = 1
AND A.RETURN_DATE <= CAST('2017-01-10 00:00:00.0' AS DATETIME)
GROUP BY B.ITEM_ID)
I am getting this error.
[Err] 42000 - [SQL Server]Incorrect syntax near '-'.
42000 - [SQL Server]Incorrect syntax near '+'
Not much to go on here for details. And we aren't actually sure if you are using mysql or sql server but pretty sure you are using sql server. I think you can accomplish what you are trying to do with something along these lines.
with Iventory as
(
SELECT i.ITEM_ID
, GoodQty = ISNULL(SUM(i.REC_GOOD_QTY), 0)
FROM INVENTORY_ITEM i
WHERE COMPANY_ID = 1
AND i.COMPANY_BRANCH_ID = 1
AND i.INV_ITEM_STATUS = 'Inward'
AND i.GRN_DATE < '2017-01-10'
GROUP BY i.ITEM_ID
)
, StockRequisition as
(
SELECT ITEM_ID
, TotalLitre = SUM(TOTAL_LITRE)
FROM STOCK_REQUISITION_ITEM B
JOIN STOCK_REQUISITION A ON A.ID = B.REQUISITION_ID
WHERE A.COMPANY_ID = 1
AND A.REQ_FROM_BRANCH_ID = 1
AND A.REQUISITION_DATE < '2017-01-10'
GROUP BY B.ITEM_ID
)
StockReturn as
(
SELECT ITEM_ID
, ReturnQuantity = SUM(RETURN_QUANTITY)
FROM STOCK_RETURN_ITEM B
JOIN STOCK_RETURN A ON A.ID = B.STOCK_RETURN_ID
WHERE A.COMPANY_ID = 1
AND A.COMPANY_BRANCH_ID = 1
AND A.RETURN_DATE <= '2017-01-10'
GROUP BY B.ITEM_ID
)
select i.ITEM_ID
, MyCalculation = i.GoodQty - isnull(Req.TotalLitre, 0) + isnull(sr.ReturnQuantity, 0)
from Inventory i
left join StockRequisition sr on sr.ITEM_ID = i.ITEM_ID
left join StockReturn Req on Req.ITEM_ID = i.ITEM_ID
In your queries you always returns two fields ITEM_ID and a numeric field.
To apply an arithmetical operation you must return one numeric field
The first query:
SELECT ITEM_ID,ISNULL(SUM(REC_GOOD_QTY),0)
becomes
SELECT ISNULL(SUM(REC_GOOD_QTY),0)
The second query:
SELECT ITEM_ID, SUM ( TOTAL_LITRE )
becomes
SELECT SUM ( TOTAL_LITRE )
The third query:
SELECT ITEM_ID, SUM ( RETURN_QUANTITY )
becomes
SELECT SUM ( RETURN_QUANTITY )
So the GROUP BY returns more than one row per query
UPDATE
i try to rewrite your query:
SELECT DISTINCT ii.item_id,
ISNULL(
(SELECT SUM(ii2.rec_good_qty)
FROM inventory_item ii2
WHERE ii2.item_id = ii.item_id
AND ii.company_id = 1
AND ii.company_branch_id = 1
AND ii.inv_item_status = 'Inward'
AND ii.grn_date < CAST('2017-01-10 00:00:00.0' AS DATETIME))
,0) -
ISNULL(
(SELECT SUM(total_litre)
FROM stock_requisition_item b
JOIN stock_requisition a
ON a.id = b.requisition_id
WHERE a.company_id = 1
AND a.req_from_branch_id = 1
AND a.requisition_date < CAST('2017-01-10 00:00:00.0' AS DATETIME))
,0) +
ISNULL(
(SELECT SUM(return_quantity)
FROM stock_return_item b
JOIN stock_return a
ON a.id = b.stock_return_id
WHERE a.company_id = 1
AND a.company_branch_id = 1
AND a.return_date <= CAST('2017-01-10 00:00:00.0' AS DATETIME))
,0) AS result
FROM inventory_item ii
WHERE ii.company_id = 1
AND ii.company_branch_id = 1
AND ii.inv_item_status = 'Inward'
AND ii.grn_date < CAST('2017-01-10 00:00:00.0' AS DATETIME)

MySql - Join not giving expected result

trying to run below query, expecting to find a match. Since my two sub-queries are same, i am expecting to find a match, which is not happening here.
select TAB_1.RUL_IDD, TAB_2.RUL_IDD
FROM
( select aaa.RUL_ID RUL_IDD from TEST_1 aaa
inner join
(
select dt,#curRank := #curRank + 1 AS rank
from (
select distinct DATE(BTCH_RUN_DTTM) dt
FROM TEST_1
where ALRT_FLG_IND = 'Y'
and PASS_IND = 'N'
and SCH_RUN_IND = 'Y'
order by DATE(BTCH_RUN_DTTM) desc
) p,
(SELECT #curRank := 0) r
order by dt desc
) zz
where DATE(aaa.BTCH_RUN_DTTM) = zz.dt
and zz.rank=1
and aaa.ALRT_FLG_IND = 'Y'
and aaa.PASS_IND = 'N'
and aaa.SCH_RUN_IND = 'Y'
) TAB_1
left outer JOIN
(
select bbb.RUL_ID as RUL_IDD from TEST_1 bbb
inner join
(
select dt,#curRank := #curRank + 1 AS rank
from (
select distinct DATE(BTCH_RUN_DTTM) dt
FROM TEST_1
where ALRT_FLG_IND = 'Y'
and PASS_IND = 'N'
and SCH_RUN_IND = 'Y'
order by DATE(BTCH_RUN_DTTM) desc
) p,
(SELECT #curRank := 0) r
order by dt desc
) zzz
on DATE(bbb.BTCH_RUN_DTTM) = zzz.dt
and zzz.rank=1
and bbb.ALRT_FLG_IND = 'Y'
and bbb.PASS_IND = 'N'
and bbb.SCH_RUN_IND = 'Y'
) TAB_2
on TAB_2.RUL_IDD = TAB_1.RUL_IDD;
Result:
enter image description here
Not getting why its not giving the expected result. TAB_2.RUL_IDD should also have same value as TAB_1.RUL_IDD. Can experts help me over here?

SQL case subquery + subquery > 0

i am trying to devide a number with another number. but because there is a chance that the result is 0 i want to make a case saying that if it is 0 then it should be 1 for this ive created this:
(CASE(SELECT COUNT(*)
FROM module_score
WHERE user_id = 40 AND medal_id > 1)
+
(SELECT COUNT(*)
FROM user_has_module_score uhms
WHERE user_id = 40 and medal_id > 1)> 0
THEN 1
ELSE 0 END) as passed_percentage
However i get the following syntax error:
medal_id > 1)> 0 THEN 1 ELSE 0 END) as passed_percentage
FROM system_learningbank.user U
WHERE U.id = 40 GROUP BY U.id
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'THEN 1 ELSE 0 END) as passed_percentage FROM system_learningbank.user U WH' at line 7
So what is the right syntax if to validate that it is not 0? and in my above example i set the variable to 1 but that should be the actual count of the subqueries
My full sql statement
SELECT
(SELECT
COUNT(*)
FROM
module_score MS
WHERE
user_id = 40) + (SELECT
COUNT(UHMS.score)
FROM
user_has_module_score UHMS
WHERE
UHMS.user_id = 40) / ((SELECT
COUNT(*)
FROM
module_score
WHERE
user_id = 40 AND medal_id > 1) + (SELECT
COUNT(*)
FROM
user_has_module_score uhms
WHERE
user_id = 40 and medal_id > 1) > 0) as passed_percentageas
FROM
system_learningbank.user U
WHERE
U.id = 40
GROUP BY U.id;
You are missing the when:
(CASE WHEN (SELECT COUNT(*) FROM module_score WHERE user_id = 40 AND medal_id > 1) +
(SELECT COUNT(*) FROM user_has_module_score uhms WHERE user_id = 40 and medal_id > 1) > 0
THEN 1 ELSE 0
END) as passed_percentage
MySQL treats booleans as integers, so you can actually write this without the case:
( (SELECT COUNT(*) FROM module_score WHERE user_id = 40 AND medal_id > 1) +
(SELECT COUNT(*) FROM user_has_module_score uhms WHERE user_id = 40 and medal_id > 1) > 0
) as passed_percentage
EDIT:
SELECT (SELECT COUNT(*)
FROM module_score MS
WHERE user_id = 40
) +
(SELECT COUNT(UHMS.score)
FROM user_has_module_score UHMS
WHERE UHMS.user_id = 40
) / ((SELECT COUNT(*)
FROM module_score
WHERE user_id = 40 AND medal_id > 1
) +
(SELECT COUNT(*)
FROM user_has_module_score uhms
WHERE user_id = 40 and medal_id > 1
) > 0
) as passed_percentageas
FROM system_learningbank.user U
WHERE U.id = 40
GROUP BY U.id;
I suspect you want something more like this:
SELECT ((ms.cnt + hms.cnt) /
(case when ms.cnt_m1 + hms.cnt_m2 > 0 then ms.cnt_m1 + hms.cnt_m2 end)
) as passed_percentageas
FROM system_learningbank.user U left join
(select userid, count(*) as cnt, sum(medal_id > 1) as cnt_m1
from module_score
group by user_id
) ms
on ms.user_id = u.user_id left join
(select userid, count(*) as cnt, sum(medal_id > 1) as cnt_m1
from user_has_module_score
group by user_id
) hms
on hms.user_id = u.user_id
WHERE U.id = 40;
However, this still looks suspicious . . . the table names suggest that only one really codes the score you want, the denominator is more restrictive than the numerator, but this structure is basically what you seem to want.
GROUP BY U.id;

MySQL Function, must bring back a row

I have this simple MySQL statement:
SELECT
((AVG(q1) + AVG(q8) + AVG(q15)) / 3 ) AS Res
FROM tresults
WHERE id = '1' AND date = 'MARCH2010' AND q25 = '1'
GROUP BY q25
Now, if there are no rows with the date MARCH2010 then the query returns zero results (which is correct) but I'd like it to return a row - even if the result is NULL.
You can just select a single row as a constant, and then left join it to your result set:
select l.*, r.*
from (select "your constant" as constant) as l
left join (
SELECT
((AVG(q1) + AVG(q8) + AVG(q15)) / 3 ) AS Res
FROM tresults
WHERE id = '1' AND date = 'MARCH2010' AND q25 = '1'
GROUP BY q25
) as r on 1
How this works:
select "your constant" as constant always returns a single row
left join always returns all of the rows in the left table at least once
if the right table has no rows, then the entire left table is extended with a bunch of null columns, and the result has one row
if the right table has n rows, the result has n rows that each have an additional "your constant" column
I'm not absolutely positive, but this case statement might work. I can't test it atm.
Case When
(SELECT
Count(*)
FROM tresults
WHERE id = '1' AND date = 'MARCH2010' AND q25 = '1'
GROUP BY q25) > 0
Then
SELECT
((AVG(q1) + AVG(q8) + AVG(q15)) / 3 ) AS Res
FROM tresults
WHERE id = '1' AND date = 'MARCH2010' AND q25 = '1'
GROUP BY q25
Else
SELECT null
End
SELECT
((AVG(q1) + AVG(q8) + AVG(q15)) / 3 ) AS Res
FROM tresults
WHERE id = '1' AND date = 'MARCH2010' AND q25 = '1'
GROUP BY q25
UNION ALL
SELECT NULL AS Res
FROM dual
WHERE NOT EXISTS (
SELECT
((AVG(q1) + AVG(q8) + AVG(q15)) / 3 ) AS Res
FROM tresults
WHERE id = '1' AND date = 'MARCH2010' AND q25 = '1'
GROUP BY q25
)
Will always return one row beacuse of second part.