1

I have this table in my database:

╔════╦═══════╦═══════╗
║ id ║ Name  ║ Price ║
╠════╬═══════╬═══════╣
║  1 ║ ciao  ║   123 ║
║  2 ║ ciao  ║    55 ║
║  3 ║ bye   ║    43 ║
║  4 ║ hello ║    12 ║
║  5 ║ ciao  ║     1 ║
║  6 ║ ciao  ║    77 ║
╚════╩═══════╩═══════╝

..and i wound like to create a new view displaying two columns:

1) "ciao" or "not ciao"

2) how many rows in the previous table are "ciao" or "not ciao", something like this:

╔════╦══════════╦═══════╗
║ id ║   Name   ║ Count ║
╠════╬══════════╬═══════╣
║  1 ║ ciao     ║     4 ║
║  2 ║ not ciao ║     2 ║
╚════╩══════════╩═══════╝

I'm trying to find a solution, but i'm not able to group by "not ciao" values:

SELECT Name, COUNT(*) 
FROM mytable
WHERE Name = "Ciao"
GROUP BY Name
0

3 Answers 3

3

You need to map everything except 'ciao' to 'not ciao', like this:

SELECT CASE WHEN Name!='ciao' THEN 'not ciao' ELSE Name END as Name, COUNT(*) 
FROM mytable
GROUP BY CASE WHEN Name!='ciao' THEN 'not ciao' ELSE Name END
Sign up to request clarification or add additional context in comments.

Comments

2

This might work (not tested) :

SELECT CASE
         WHEN name = 'ciao' THEN 'ciao'
         ELSE 'not ciao'
       END as NAME,
       COUNT(*)
FROM   table
GROUP  BY CASE
            WHEN name = 'ciao' THEN 'ciao'
            ELSE 'not ciao'
          END 

OR in MySQL

SELECT CASE
         WHEN name = 'ciao' THEN 'ciao'
         ELSE 'not ciao'
       END as NAME1,
       COUNT(*)
FROM   table
GROUP  BY NAME1

Comments

1

Easiest way:

SELECT Name, COUNT(*) 
FROM
(select case when name <> "Ciao" then "Not Ciao"
                  else "Ciao" end as name
 from mytable)
GROUP BY Name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.