Sql query with three conditions - mysql

I have a database with a table having content as below :
message_number message_type message_chat
0 IN Hi
1 OB Hello
2 IN Help
3 IN Want to find this thing
4 OB Sure
5 OB Please let me know
I have written 5 rows since i want to incorporate all possible cases that i want in my query in the example table that i showed.
Now in my query output, i want something like :
message_in message_out
Hi Hello
Help NULL
Want to find this string Sure
NULL Please let me know
So the cases that i want to consider are :
suppose if message_number=0 and message_number=1 both have message_type value as IN then put message_chat_in as message_chat(at message_number=0) and message_chat out as NULL and the iterate over message_number=1
if message_number =0 have message_type=IN and message_number =1 have message_type=OB, then show message_chat(at message_number=0) as message_chat_in and message_chat(at message_number=1) as message_out and dont iterate over message_number=1;
hope i have clarified the condition though i have included all three condition in the expected output.How should my sqlquery look like?
Edit : I am using mysql version 5.5.8

Try the following query
SELECT
q1.message_number in_num,
q1.message_chat in_chat,
q2.message_number out_num,
q2.message_chat out_chat
FROM
(
SELECT *,#i1:=IFNULL(#i1,0)+1 num
FROM Chat
ORDER BY message_number
) q1
LEFT JOIN
(
SELECT *,#i2:=IFNULL(#i2,0)+1 num
FROM Chat
ORDER BY message_number
) q2
ON q2.num=q1.num+1 AND q2.message_type<>q1.message_type
WHERE q1.message_type='IN'
UNION ALL
SELECT
q1.message_number in_num,
q1.message_chat in_chat,
q2.message_number out_num,
q2.message_chat out_chat
FROM
(
SELECT *,#i3:=IFNULL(#i3,0)+1 num
FROM Chat
ORDER BY message_number
) q1
RIGHT JOIN
(
SELECT *,#i4:=IFNULL(#i4,0)+1 num
FROM Chat
ORDER BY message_number
) q2
ON q2.num=q1.num+1 AND q2.message_type<>q1.message_type
WHERE q2.message_type='OB'
AND q1.message_type IS NULL
ORDER BY IFNULL(in_num,out_num)
SQL Fiddle - http://sqlfiddle.com/#!9/95a515/1
The second variant
SET #i1 = 0;
SET #i2 = 0;
SET #i3 = 0;
SET #i4 = 0;
-- the same query
SQL Fiddle - http://sqlfiddle.com/#!9/95a515/2
Or
SELECT 0,0,0,0 INTO #i1,#i2,#i3,#i4;
-- the same query
SQL Fiddle - http://sqlfiddle.com/#!9/95a515/5

why not using a analytic function here? I would do it with Lead() like this:
with inc as (
--Do the incorporation in this block. could be subquery too
--but its easier to read this way.
select
case when message_type = 'IN'
then message_chat
end as message_in
,case when LEAD(message_type) OVER (Order by message_number) = 'OB' --get the next message by number if it is type OB
then LEAD(message_chat) OVER (order by message_number)
end as message_out
from input
)
select *
from inc
where coalesce(message_in, message_out) is not null --filter out rows where with in & out is null

Ok, since there is no analytical functions in MySQL less than 8 the code may not be easy to follow:
with data_rn as
(
-- this isolate consecutive rows with the same message_type
select d1.*, count(d2.message_number) rn
from data d1
left join data d2 on d1.message_number > d2.message_number and d1.message_type != d2.message_type
group by d1.message_number
),
data_rn2 as
(
-- this marks the rows where new rows has to be added (i.e. when rn2 != 0)
select d1.*, count(d2.message_number) rn2
from data_rn d1
left join data_rn d2 on d1.rn = d2.rn and d1.message_type = d2.message_type and d1.message_number > d2.message_number
group by d1.message_number
),
data_added as
(
-- this add new rows
select message_number, message_type, message_chat
from data_rn2
union all
select message_number - 0.5, 'OB', NULL from data_rn2 where message_type = 'IN' and rn2 != 0
union all
select message_number - 0.5, 'IN', NULL from data_rn2 where message_type = 'OB' and rn2 != 0
order by message_number
), data_added_rn as
(
-- this compute new row numbering
select d1.*, ceil((count(d2.message_number)+1)/2) rn
from data_added d1
left join data_added d2 on d1.message_number > d2.message_number
group by d1.message_number
)
-- this will do the final formating
select max(case when message_type = 'IN' then message_chat end) message_in,
max(case when message_type = 'OB' then message_chat end) message_out
from data_added_rn
group by rn
demo
I have tried to comment each section appropriately.

Related

MYSQL error code: 1054 Unknown column in where clause. Error occurring in Nested SubQueries

I am trying to get through a problem where there are multiple accounts of same scheme on same customer id. On a given txn date I want to retrieve the total Sanctioned Limit and total utilized amount from these accounts. Below is the SQL query I have constructed.
SELECT
cust_id,
tran_date,
rollover_date,
next_rollover,
(
SELECT
acc_num as kcc_ac
FROM
dbzsubvention.acc_disb_amt a
WHERE
(a.tran_date <= AB.tran_date)
AND a.sch_code = 'xxx'
AND a.cust_id = AB.cust_id
ORDER BY
a.tran_date desc
LIMIT
1
) KCC_ACC,
(
SELECT
SUM(kcc_prod)
FROM
(
SELECT
prod_limit as kcc_prod,
acc_num,
s.acc_status
FROM
dbzsubvention.acc_disb_amt a
inner join dbzsubvention.acc_rollover_all_sub_status s using (acc_num)
left join dbzsubvention.acc_close_date c using (acc_num)
WHERE
a.cust_id = AB.cust_id
AND a.tran_date <= AB.tran_date
AND (
ac_close > AB.tran_date || ac_close is null
)
AND a.sch_code = 'xxx'
AND s.acc_status = 'R'
AND s.rollover_date <= AB.tran_date
AND (
AB.tran_date < s.next_rollover || s.next_rollover is null
)
GROUP BY
acc_num
order by
a.tran_date
) t
) kcc_prod,
(
SELECT
sum(disb_amt)
FROM
(
SELECT
disb_amt,
acc_num,
tran_date
FROM
(
SELECT
disb_amt,
a.acc_num,
a.tran_date
FROM
dbzsubvention.acc_disb_amt a
inner join dbzsubvention.acc_rollover_all_sub_status s using (acc_num)
left join dbzsubvention.acc_close_date c using (acc_num)
WHERE
a.tran_date <= AB.tran_date
AND (
c.ac_close > AB.tran_date || c.ac_close is null
)
AND a.sch_code = 'xxx'
AND a.cust_id = AB.cust_id
AND s.acc_status = 'R'
AND s.rollover_date <= AB.tran_date
AND (
AB.tran_date < s.next_rollover || s.next_rollover is null
)
GROUP BY
acc_num,
a.tran_date
order by
a.tran_date desc
) t
GROUP BY
acc_num
) tt
) kcc_disb
FROM
dbzsubvention.acc_disb_amt AB
WHERE
AB.cust_id = 'abcdef'
group by
cust_id,
tran_date
order by
tran_date asc;
This query isn't working. Upon research I have found that correlated subquery works only till 1 level down. However I couldn't get a workaround to this problem.
I have tried searching the solution around this problem but couldn't find the desired one. Using the SUM function at the inner query will not give desired results as
In the second subquery that will sum all the values in column before applying the group by clause.
In third subquery the sorting has to be done first then the grouping and finally the sum.
Therefore I am reaching out to the community for help to suggest a workaround to the issue.
You're correct - external column cannot be transferred through the nesting level immediately.
Try this workaround:
SELECT ... -- outer query
( -- correlated subquery nesting level 1
SELECT ...
( -- correlated subquery nesting level 2
SELECT ...
...
WHERE table0_level1.column0_1 ... -- moved value
)
FROM table1
-- move through nesting level making it a source of current level
CROSS JOIN ( SELECT table0.column0 AS column0_1 ) AS table0_level1
) AS ...,
...
FROM table0
...

MYSQL - Subqueries problem - Cant reuse the table

WITH t as (
SELECT *
FROM scd p
WHERE p.modified_date > FROM_UNIXTIME(1593060230)
AND ( p.main_id = 1
OR FIND_IN_SET(1, p.mult_ids) <> 0 )
ORDER BY modified_date DESC
LIMIT 2 OFFSET 0
),
del as (
SELECT
*
FROM t WHERE (status <> 1 AND status <> 2)
),
w_del as (
SELECT
*
FROM t WHERE (status = 1 OR status = 2)
)
SELECT w_del.*, del.* FROM w_del,del;
How do I achieve this with normal sub queries. I am using MySQL 5.7 and can't use CTEs. Im getting can't reuse table error if I use UNION/sub-queries. Is there a way to achieve this without temporary tables?
Please help.
You can just plug in the code for each alias . . . and keep doing that until you are at the base tables:
SELECT w_del.*, del.*
FROM (SELECT t.*
FROM (SELECT *
FROM scd p
WHERE p.modified_date > FROM_UNIXTIME(1593060230) AND
( p.main_id = 1 OR FIND_IN_SET(1, p.mult_ids) <> 0 )
ORDER BY modified_date DESC
LIMIT 2 OFFSET 0
) t
WHERE (status <> 1 AND status <> 2)
) w_del CROSS JOIN
(SELECT t.*
FROM (SELECT *
FROM scd p
WHERE p.modified_date > FROM_UNIXTIME(1593060230) AND
( p.main_id = 1 OR FIND_IN_SET(1, p.mult_ids) <> 0 )
ORDER BY modified_date DESC
LIMIT 2 OFFSET 0
) t
WHERE (status = 1 OR status = 2)
) del;
One critical point, though: The definition of t is using ORDER BY and LIMIT. If there are ties in the modified_date column, then the two subqueries could return different result sets. You have two choices to avoid a problem here:
Add additional keys to the ORDER BY to ensure that the sorting is stable (i.e. returns the same results each time because the combination of keys is unique).
Materialize the subquery using a temporary table.

1242 Subquery returns more than 1 row

I got this error, I hope you may help me. I want to show a certain item in a search.
SELECT p.id, p.property_rank, p.pic_numb, p.att_numb, p.confirm, p.finalized ,p.deleted, p.user_id, p.add_date, p.visit_time,p.visit_date,p.sent_numb, p.contact_numb, zip_name, zip_id, p.street, p.sp_featured, p.property_title, p.b_price_unit, p.b_price_si, p.b_price, p.b_price, p.street_no, p.field_54,
p.field_409,
( SELECT `listing_type`.`id`
FROM `res_rpl_listing_types` AS `listing_type`
WHERE `listing_type`.`id` = (
SELECT `listing`.`type`
FROM `res_rpl_listings` AS `listing`
WHERE `listing`.`id` = p.`listing`)
) AS `listing_type_id`,
p.listing, p.googlemap_ln, p.googlemap_lt, p.category, p.b_bedrooms, p.b_bathrooms, p.sp_openhouse, p.b_price_period, p.b_lot_area_unit, p.b_lot_area_si, p.b_lot_area, p.b_lot_area, p.b_living_area_unit, p.b_living_area_si, p.b_living_area, p.b_living_area, p.description, p.sp_hot, p.sp_forclosure
FROM res_rpl_properties AS p
WHERE 1 AND p.`type` = '0' AND p.`confirm` = '1' AND p.`finalized` = '1' AND p.`deleted` = '0' AND p.`category` IN(9,8,10)
ORDER BY p.add_date DESC
LIMIT 0 , 12
The error is telling you that your subquery (selected as listing_type_id) returns more than one row. To rephrase - it's returning more than one value for listing_type_id. You should limit the results from the subquery to just one.
You have two options:
OR select just the first row of subquery
(SELECT `listing_type`.`id`
FROM `res_rpl_listing_types` AS `listing_type`
WHERE `listing_type`.`id` = (
SELECT `listing`.`type`
FROM `res_rpl_listings` AS `listing`
WHERE `listing`.`id` = p.`listing`
LIMIT 1
)
LIMIT 1
) AS `listing_type_id`
OR use IN to allow multiple comparation
(SELECT `listing_type`.`id`
FROM `res_rpl_listing_types` AS `listing_type`
WHERE `listing_type`.`id` IN (
SELECT `listing`.`type`
FROM `res_rpl_listings` AS `listing`
WHERE `listing`.`id` = p.`listing`)
LIMIT 1
) AS `listing_type_id`
The problem is there is 2 subqueries and you need to treat both. Both of them need to be limited to 1 row only.

Mysql Group by With Condition

The below data shows time schedule having elective/ non-elective subjects of a student. My requirement is to select those rows when both elec and nonelec type has same period so in this case select elec type. Means for a day's schedule elective (type elec) should be given preference when both having same period. And when type elec does not has period like period 5 then select the non-elective one.
My Query
SELECT s.sch_id, s.sch_subtype, sd.sdetail_id, sd.sdetail_period
FROM schedule s
INNER JOIN schedule_detail sd ON s.sch_id = sd.sdetail_schedule
WHERE '2014-04-30'
BETWEEN sch_datefrom
AND sch_dateto
AND
(
(
sch_section =1
AND sch_subtype = 'nonelec'
)
OR
(
sch_subtype = 'elec'
AND 272
IN
(
SELECT edetail_stuid
FROM elective_detail
WHERE edetail_elective = sch_section
)
)
)
AND sch_course =3
AND sch_batch =2
AND sch_termid =2
AND sdetail_day = 'wed'
AND sdetail_period >0
AND CASE WHEN sch_subtype = 'nonelec'
THEN 1 =1
WHEN sch_subtype = 'elec'
THEN sdetail_subject >0
AND sdetail_faculty >0
AND sdetail_room >0
END GROUP BY CASE WHEN sch_subtype = 'elec'
THEN sdetail_period
ELSE 1
END ORDER BY sdetail_period
Output of above query
Required Output
You can try something of this sort :
SELECT sch_id,sch_subtype,sdetail_id,sdetail_period
FROM table
WHERE condition
group by sch_subtype
It would be better if you can post the query which u tried.
Dont really get whats the problem here:
SELECT * FROM schedule s
JOIN schedule_detail sd ON s.sch_id = sd.sdetail_schedule
LEFT JOIN elective_detail ed ON sd.sch_section = ed.edetail_elective
WHERE
(
sd.sch_section =1
AND s.sch_subtype = 'nonelec'
)
OR
(
ed.edetail_stuid = 227
AND sch_subtype = 'elec'
)
GROUP BY sd.sdetail_period
SQL Fiddle: http://sqlfiddle.com/#!2/69d4e/1

MySQL - query to return NULL

I have the following code:
SELECT q25, (
(
AVG( q1 ) + AVG( q2 ) + AVG( q3 ) ) /3 ) AS Overall
FROM t_results
WHERE brand = 'XYZ'
AND DATE = 'MAY2012'
GROUP BY q25
ORDER BY Overall
DESC LIMIT 1
If there is no data found by the query phpmyadmin returns the following message (which is quite correct):
MySQL returned an empty result set (i.e. zero rows). ( Query took 0.0178 sec )
However, what I'd like is to actually return a NULL value, is this possible? I appreciate this might not be best practise but I'm working with inherited code and this might be the simplist and quickest route to a solution.
Thanks as always,
H.
Create a table with exactly one row. Then you can use left join to achieve the desired NULL result.
CREATE TABLE dummy (d TINYINT NOT NULL);
INSERT INTO dummy SET d = 1;
SELECT q25,
( ( AVG( q1 ) + AVG( q2 ) + AVG( q3 ) ) /3 ) AS Overall
FROM dummy LEFT JOIN t_results
ON brand = 'XYZ'
AND DATE = 'MAY2012'
GROUP BY q25
ORDER BY Overall DESC
LIMIT 1
You can also replace the dummy table with a subquery:
SELECT q25,
( ( AVG( q1 ) + AVG( q2 ) + AVG( q3 ) ) /3 ) AS Overall
FROM (SELECT 1) AS dummy LEFT JOIN t_results
ON brand = 'XYZ'
AND DATE = 'MAY2012'
GROUP BY q25
ORDER BY Overall DESC
LIMIT 1
Tested this via sqlfiddle, where you can also experiment with alternatives.
The conditions selecting the result, which used to be in the WHERE clause, now have to go into the ON clause. Otherwise the left join would produce non-NULL rows which would be removed by the WHERE, instead of generating a single NULL row if no matching row could be found. If there were no WHERE conditions in the original query, ON 1 could be used to express any row matches.
You can use a UNION combined with a LIMIT to supply the NULL values:
(SELECT q25,
(AVG(q1) + AVG(q2) + AVG(q3))/3 AS Overall
FROM t_results
WHERE brand = 'XYZ'
AND DATE = 'MAY2012'
GROUP BY q25
ORDER BY Overall DESC
LIMIT 1
)
UNION ALL
(SELECT NULL, NULL)
LIMIT 1;
This only works when you know that the first query will never yield more than one result, though. Which is the case here, so this might be the best solution for you, but the approach given in my other answer is more general.
There is a fiddle for this to experiment with.
The coalesce() function can be used to return the first non-null value from a number of comma separated columns or strings. The values/columns are evaluated left to right, so if you want to pop a string into the arguments that isn't null, make sure you place it to the right of the columns that you are testing against.
select
coalesce(
(
SELECT
q25
FROM
t_results
WHERE
brand = 'XYZ'
AND DATE = 'MAY2012'
GROUP BY
q25
LIMIT 1
), 'null') as q25,
coalesce(
(
SELECT
((AVG( q1 ) + AVG( q2 ) + AVG( q3 ) ) /3 ) AS Overall
FROM t_results
WHERE
brand = 'XYZ'
AND DATE = 'MAY2012'
LIMIT 1
), 'null') as Overall
from
t_results
group by
1, 2;
If you don't have data that matches your where clause, this will return null, null as a row.