简体   繁体   中英

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'

+------+-------+-------+-------+-------+
| 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

+------+------+
| 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? I use php on Symfony2.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM