计算不存在的列行

时间:2014-03-04 07:30:47

标签: mysql

我正在尝试计算列的行数。在这样做时我遇到了这个问题

这是我的数据,例如

我有2列 ID ANSWERS 列ID的值为A {是,是,否,否,可能,也许} 列ANSWERS的值为B {是,是,否}

我正在尝试过滤答案,我只想计算“可能”的值。所以我想得到的最终答案是

A列{2] - A栏中有2个“可能”值 B列{0} - B列中有“可能”的0值

我使用了这个查询

select id, answers, count(*) as count from my_database
where answers = 'maybe' 
group by id, answers

此查询仅向我提供表格列中“已存在”的计数。

我希望你们能理解我的解释。谢谢!

2 个答案:

答案 0 :(得分:0)

select id, answers, count(*) as count from my_database
where answers = 'maybe' 
group by answers, id;

答案 1 :(得分:0)

如果各列列值具有重复字词,则无法对其应用count。 相反,您可以计算单个行的列值中特定模式的出现次数。

示例

mysql> set @mb='A{yes,yes,no,no,maybe,maybe}';
Query OK, 0 rows affected (0.00 sec)

mysql> select @mb,
    ->    @len1:=length( @mb ) len1,
    ->    @rp1:=replace( @mb, 'maybe', '' ) rp1,
    ->    @len2:=length( @rp1 ) len2,
    ->    @dif:=( @len1 - @len2 ) dif,
    ->    @len3:=length( 'maybe' ) len3,
    ->    @cnt:=cast( @dif/@len3 as decimal ) cnt;
+------------------------------+------+--------------------+------+------+------+------+
| @mb                          | len1 | rp1                | len2 | dif  | len3 | cnt  |
+------------------------------+------+--------------------+------+------+------+------+
| A{yes,yes,no,no,maybe,maybe} |   28 | A{yes,yes,no,no,,} |   18 |   10 |    5 |    2 |
+------------------------------+------+--------------------+------+------+------+------+

在您的表上查询后的数据可能有效。

select 
  id, answers, 
  cast( ( length(ID) - length( replace( ID, 'maybe', '' ) ) )
        / length('maybe')
        as decimal ) cnt 
from my_database
where answers = 'maybe' 

如果您仍希望每个count使用ID特定模式,请在上述解决方案中使用group by

select id, answers, sum(cnt) as total_count
from (
  select 
    id, answers, 
    cast( ( length(ID) - length( replace( ID, 'maybe', '' ) ) )
          / length('maybe')
          as decimal ) cnt 
  from my_database
  where answers = 'maybe' 
) tmp
group by id, answers