我的数据库中有这个表:
╔════╦═══════╦═══════╗
║ id ║ Name ║ Price ║
╠════╬═══════╬═══════╣
║ 1 ║ ciao ║ 123 ║
║ 2 ║ ciao ║ 55 ║
║ 3 ║ bye ║ 43 ║
║ 4 ║ hello ║ 12 ║
║ 5 ║ ciao ║ 1 ║
║ 6 ║ ciao ║ 77 ║
╚════╩═══════╩═══════╝
…我想创建一个显示两列的新视图:
1)“再见”或“不再见”
2)上表中有多少行是“ciao”或“not ciao”,如下所示:
╔════╦══════════╦═══════╗
║ id ║ Name ║ Count ║
╠════╬══════════╬═══════╣
║ 1 ║ ciao ║ 4 ║
║ 2 ║ not ciao ║ 2 ║
╚════╩══════════╩═══════╝
我试图找到一个解决方案,但我无法按“不ciao”值分组:
SELECT Name, COUNT(*)
FROM mytable
WHERE Name = "Ciao"
GROUP BY Name
最佳答案
这可能有效(未测试):
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中
SELECT CASE
WHEN name = 'ciao' THEN 'ciao'
ELSE 'not ciao'
END as NAME1,
COUNT(*)
FROM table
GROUP BY NAME1
关于mysql - 使用GROUP BY语句的SQL查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28858133/