2017-06-15 65 views
0

給定以下數據;MySql - 僅由具有特定值的列進行分組(無UNION)

column a | column b | column c 
________ ________ _______ 
    A  | apple | 1 
    P  | pear  | 3 
    O  | orange | 4 
    A  | apple | 1 
    P  | peach | 2 
    P  | pear  | 3 
    P  | peach | 1 
    A  | apple | 4 

我想選擇和只有組(和總和)由蘋果。其餘列不會被分組,因此以下是輸出;

column a | column b | column c 
________ ________ _______ 
    A  | apple | 6 
    P  | pear  | 3 
    O  | orange | 4 
    P  | peach | 2 
    P  | pear  | 3 
    P  | peach | 1 

是上述可能不使用UNION

+0

你有任何價值列'了'其中B列不等於蘋果嗎? –

+0

@PaulKaram不,實際上如果不適用於蘋果分組記錄的目的,這個列可以簡單地標記爲「不適用」。 – dre

回答

2

,不使用UNION

SELECT tbl.id,tbl.a,tbl.b,tbl.c FROM (
SELECT id,a, 
    CASE WHEN b='apple' THEN @ap:= (@ap+c) ELSE c END as c, 
    CASE WHEN b = (SELECT b FROM fruit WHERE id > frA.id AND b='apple' LIMIT 1) THEN b ELSE CONCAT(' ',b) END as b 
    FROM fruit AS frA, (SELECT @ap:=0) AS apc 
    ) as tbl 
WHERE tbl.b REGEXP '^[ ].*$' 

現場演示:SQL Fiddle

相關問題