我在mysql数据库中有表,在该表中我做了一些查询来显示表中的结果。但是我想在我的表中合并一些行。
这是我表的结构和示例值。
id | benefit | plan_day | price
-------------------------------
1 | Free Pick up | 100 | 540
2 | Free Tea | 100 | 540
该示例在 plan_day 中具有相同的值,但在效益中具有不同的值。
这是我的第二个例子, plan_day 和好处
不同id | benefit | plan_day | price
-------------------------------
1 | Free Pick up | 110 | 540
2 | Free Tea | 100 | 540
我想知道的是,如果 plan_day 中的值相同,我想将这两行与条件合并我只想要合并好处和价格不是SUM
但是如果 plan_day 有不同的价值我想合并好处和 plan_day 本身和我想要SUM
价格。
这是我想要显示的结果:
如果 plan_day 具有相同的值,则为条件。
Free Pick up, Free Tea | 100 | 540
如果 plan_day 具有不同的值,则为条件。
Free Pick up, Free Tea | 110, 100 | 1080
这就是我一直在做但不成功的事。
SELECT GROUP_CONCAT(benefit SEPARATOR ',') AS benefit, GROUP_CONCAT(plan_day SEPARATOR ',') AS plan_day, SUM(price) as price
FROM special_offer
任何人都可以帮我解决这个问题吗?谢谢。
答案 0 :(得分:1)
只需在查询中添加DISTINCT
子句:
SELECT
GROUP_CONCAT(DISTINCT benefit SEPARATOR ',') AS benefit,
GROUP_CONCAT(DISTINCT plan_day SEPARATOR ',') AS plan_day,
SUM(price) as price
FROM
special_offer
答案 1 :(得分:0)
我想你想要这个:
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;
对于这些数据:
(1, 'Free Pick up', 110, 540 ),
(2, 'Free Tea', 100, 540 );
产地:
110,100 Free Pick up,Free Tea 1080
对于数据
(1, 'Free Pick up', 100, 540 ),
(2, 'Free Tea', 100, 540 );
产地:
100 Free Pick up,Free Tea 540