I have table in mysql database and in that table I do some query to display result from the table. But I want to merge some row in my table.
This is the structure and example value of my table.
id | benefit | plan_day | price
-------------------------------
1 | Free Pick up | 100 | 540
2 | Free Tea | 100 | 540
That example have same value in plan_day but different value in benefit .
This is my second example with different in plan_day and benefit
id | benefit | plan_day | price
-------------------------------
1 | Free Pick up | 110 | 540
2 | Free Tea | 100 | 540
What I want to know is I want to merge that two rows with condition if the value in plan_day is the same I just want merge benefit and the price is not SUM
but if plan_day have different value I want to merge benefit and that plan_day itself and I want to SUM
the price .
This is result I want to display :
Condition if plan_day have same value.
Free Pick up, Free Tea | 100 | 540
Condition if plan_day have different value.
Free Pick up, Free Tea | 110, 100 | 1080
And this is what I have been do but not success.
SELECT GROUP_CONCAT(benefit SEPARATOR ',') AS benefit, GROUP_CONCAT(plan_day SEPARATOR ',') AS plan_day, SUM(price) as price
FROM special_offer
Anyone can help me with this issue ? Thank you.
Just add the DISTINCT
clause to your query:
SELECT
GROUP_CONCAT(DISTINCT benefit SEPARATOR ',') AS benefit,
GROUP_CONCAT(DISTINCT plan_day SEPARATOR ',') AS plan_day,
SUM(price) as price
FROM
special_offer
I think you want this:
select plan_day,
group_concat(benefit order by id separator ',') benefits,
max(price) price
from t
group by plan_day
having count(*) > 1
union all
select *
from (
select group_concat(t1.plan_day order by t1.id separator ',') plan_day,
group_concat(t1.benefit order by t1.id separator ','),
sum(t1.price) price
from t t1
join (
select plan_day
from t
group by plan_day
having count(*) = 1
) t2 on t1.plan_day = t2.plan_day
)
where plan_day is not null;
For this data:
(1, 'Free Pick up', 110, 540 ),
(2, 'Free Tea', 100, 540 );
Produces:
110,100 Free Pick up,Free Tea 1080
And for data
(1, 'Free Pick up', 100, 540 ),
(2, 'Free Tea', 100, 540 );
Produces:
100 Free Pick up,Free Tea 540
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.