[英]Sql statement query count data
I start to learn how to write sql language but I got stuck with the problem below : Now I have a data in a table named 'data' 我开始学习如何编写sql语言,但遇到以下问题:现在我在名为“数据”的表中有一个数据
+------+-------+-------+-------+-------+
| id | name | type1 | type2 | type3 |
+------+-------+-------+-------+-------+
| 1 | Cake | a | b | f |
| 2 | Coca | a | d | c |
| 3 | Ice | c | b | a |
| 4 | Wine | c | e | d |
| 5 | Salad | c | f | a |
| 6 | Water | d | e | f |
+------+-------+-------+-------+-------+
I want to write an sql statement to count all type that present in type1, type2, type3 so the result I want to get is 我想编写一条sql语句以计算出现在type1,type2,type3中的所有类型,所以我想要得到的结果是
+------+------+
| type | count|
+------+------+
| a | 4 |
| b | 2 |
| c | 4 |
| d | 3 |
| e | 2 |
| f | 3 |
+------+------+
Assume that we don't exactly knew how many different types and number of column, so can you kindly guide me how to deal with this problem? 假定我们不完全知道多少种不同类型和数量的列,那么您能指导我如何处理此问题吗? Oh should I solve it in level programming language not the sql?
哦,我应该用级别编程语言而不是sql解决它吗? I use php on Symfony2.
我在Symfony2上使用php。
Thanks in advance, 提前致谢,
SELECT type, COUNT(*) count
FROM
(
SELECT type1 type FROM data
UNION ALL
SELECT type2 type FROM data
UNION ALL
SELECT type3 type FROM Data
) AS subquery
GROUP BY type
OUTPUT 输出值
╔══════╦═══════╗
║ TYPE ║ COUNT ║
╠══════╬═══════╣
║ a ║ 4 ║
║ b ║ 2 ║
║ c ║ 4 ║
║ d ║ 3 ║
║ e ║ 2 ║
║ f ║ 3 ║
╚══════╩═══════╝
An approach that should only require one scan of the data table: 一种只需要对数据表进行一次扫描的方法:
select type, count(*) from
(select case t.typeno
when 1 then d.type1
when 2 then d.type2
when 3 then d.type3
end type
from (select 1 typeno union all select 2 typeno union all select 3 typeno) t
cross join data d
) sq
group by type
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.