[英]Merge two rows in mysql database table with condition
我在mysql數據庫中有表,並且在該表中我做了一些查詢以顯示表的結果。 但是我想合並表中的某些行。
這是我的表的結構和示例值。
id | benefit | plan_day | price
-------------------------------
1 | Free Pick up | 100 | 540
2 | Free Tea | 100 | 540
這個例子有plan_day相同的價值,但在利益不同的值。
這是我的第二個示例,其plan_day和benefit不同
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
任何人都可以幫助我解決這個問題? 謝謝。
只需將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
我想你想要這個:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.