SQL QUERY:复合

时间:2011-09-14 13:52:39

标签: mysql

有MySQL的查询。这个查询可以在前端轻松解决,但在MySQL中需要一个机制。 你如何计算1列中的2个不同的项目? 例如: 我有这张桌子:

NAME    FRUIT
A   APPLE
A   APPLE
A   ORANGE
A   APPLE
A   ORANGE
B   APPLE
B   ORANGE
B   ORANGE
B   ORANGE

需要o / P:

NAME    No._of_apples   No._of_oranges
A   3            2
B   1            3

任何人都可以澄清我试过的代码,以获得这个O / P:

select distinct msisdn, count(fruit) no._of_apples, count(fruit) no._of_oranges
from table,

where true

group by 1
order by 1

1 个答案:

答案 0 :(得分:1)

SELECT NAME, 
       SUM(IF(FRUIT = 'APPLE', 1, 0)) AS no_of_apples,
       SUM(IF(FRUIT = 'ORANGE', 1, 0)) AS no_of_oranges
FROM table
GROUP BY NAME
ORDER BY NAME