Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 646
andrefadila Avatar asked Apr 24 '13 08:04

andrefadila


People also ask

How do you check if two values are the same in MySQL?

In MySQL, you can use the = operator to test for equality in a query. The = operator can only test equality with values that are not NULL. For example: SELECT * FROM contacts WHERE last_name = 'Johnson';

How do I check if two columns are not equal in SQL?

We can use both SQL Not Equal operators <> and != to do inequality test between two expressions. Both operators give the same output. The only difference is that '<>' is in line with the ISO standard while '!=

How will you compare successive rows within the same table in MySQL?

Here's the SQL query to compare each row with previous row. In the above query, we join sales table with itself using an INNER JOIN condition g2.id=g1.id + 1 that allows you to compare each row with its previous row. Please note, this condition depends on the fact that our id column has consecutive numbers.


1 Answers

SELECT  jamu_a,
        jamu_b,
        GROUP_CONCAT(khasiat) khasiat,
        COUNT(*) total
FROM    TableName
GROUP   BY  jamu_a, jamu_b
  • SQLFiddle Demo
  • MySQL GROUP_CONCAT()

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
like image 186
John Woo Avatar answered Sep 28 '22 14:09

John Woo