2017-03-09 47 views
0

我有mysql數據庫中的表,並在該表中執行一些查詢以顯示錶中的結果。但我想合併表格中的某一行。合併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

會發生什麼?如果plan_day相同但價格不同,會發生什麼情況? – GurV

+0

我只想顯示一個。 @GurV – Antonio

+0

哪一個?請說明在這種情況下它將如何工作? – GurV

回答

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 
+0

也許是一個好主意'按價格組' – Orangepill

+0

對不起,我只是編輯我的問題的一部分查詢和結果我想要的。我更改'SUM(價格)AS價格' – Antonio

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 
+0

當plan_day不同時,它返回空。 – Antonio

+0

@Antonio - 不,它沒有。查看第一個示例輸出。 – GurV

+0

你有其他簡單的查詢嗎?不是像那樣的工會? – Antonio