简体   繁体   中英

MySQL compare same values in two column

I have a data in my database like this :

jamu_a | jamu_b | khasiat

A      | B      | Z
A      | B      | X
A      | B      | C

And then, I want an output like this :

jamu_a | jamu_b | khasiat | total

A      | B      | Z, X, C | 3

I'm not expert in MySQL, what kind of query to produce an output like that? Tell me if MySQL can't do that and need some programming language. Thanks in advance

SELECT  jamu_a,
        jamu_b,
        GROUP_CONCAT(khasiat) khasiat,
        COUNT(*) total
FROM    TableName
GROUP   BY  jamu_a, jamu_b

OUTPUT

╔════════╦════════╦═════════╦═══════╗
║ JAMU_A ║ JAMU_B ║ KHASIAT ║ TOTAL ║
╠════════╬════════╬═════════╬═══════╣
║ A      ║ B      ║ Z,X,C   ║     3 ║
╚════════╩════════╩═════════╩═══════╝

if there are repeating values on column KHASIAT and you want it to be unique, you can add DISTINCT on GROUP_CONCAT()

SELECT  jamu_a,
        jamu_b,
        GROUP_CONCAT(DISTINCT khasiat) khasiat,
        COUNT(*) total
FROM    TableName
GROUP   BY  jamu_a, jamu_b

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM