使用GROUP BY语句的SQL查询

时间:2015-03-04 15:21:53

标签: mysql sql group-by

我的数据库中有这个表:

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

..我想创建一个显示两列的新视图:

1)" ciao"或者"不是ciao"

2)上一表中有多少行是" ciao"或者"不是ciao",像这样:

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

我试图找到一个解决方案,但我无法按照"而不是ciao"值:

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

3 个答案:

答案 0 :(得分:3)

您需要将'ciao'以外的所有内容映射到'not ciao',如下所示:

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

答案 1 :(得分:2)

这可能有用(未经测试):

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 

MySQL中的OR

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

答案 2 :(得分:1)

最简单的方法:

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