按嵌套查询中存在的字段分组

时间:2015-05-31 19:19:26

标签: mysql

我想感谢你为答案做出贡献,这是一个SQL小提琴

http://sqlfiddle.com/#!9/610e7/1

- 此查询将返回问题的所有属性

select * from dataissue where issue = '25998'

我想做的是:

sum(value) count(value)    

where field = 'version(s)_corrigée(s)'

and value  = 'Fermée' 

and  field = 'point_d_effort'

and value = 'récit'

and group it by value where field = 'version(s)_corrigée(s)' 

例如,此查询返回组,但总和会爆炸,因为我们使用外部查询的字段:

sqlfiddle.com /#!9 / 610e7 / 4

1 个答案:

答案 0 :(得分:0)

我怀疑你想要这样的东西:

select sum(case when field = 'point_d_effort' then value + 0 end), as v 
       sum(field = 'point_d_effort') as cnt
from dataissue
group by issue
having sum(field = 'version(s)_corrigée(s)' and value  = 'Fermée') > 0 and
       sum(field = 'Type de demande' and value = 'récit')  > 0;

您有一个实体 - 属性 - 值(EAV)数据结构。一种方法是首先按键聚合。如果您想要所有问题的总数,那么您需要另一个聚合:

select sum(v), sum(cnt)
from (select sum(case when field = 'point_d_effort' then value + 0 end), as v 
             sum(field = 'point_d_effort') as cnt
      from dataissue
      group by issue
      having sum(field = 'version(s)_corrigée(s)' and value  = 'Fermée') > 0 and
             sum(field = 'Type de demande' and value = 'récit')  > 0
    ) t