按嵌套查询中的字段分组

时间:2015-05-30 17:04:48

标签: mysql

我们有一个嵌套的SQL查询,我们希望按嵌入查询中的字段进行分组,而不是按主查询上的字段进行分组。

SELECT dataissue.value as a,
    COUNT(value),
    substring(issue.entry, 1, 3) 
FROM DataIssue, issue 
WHERE field = 'point_d_effort' 
  AND dataissue.issue = issue.id  

  AND issue IN (
         SELECT issue
         FROM dataissue, issue 
         WHERE dataissue.issue = issue.id 
           AND value = 'récit' 
           AND substring(issue.entry,1,3) = 'ema'
  ) 
  AND issue IN (
         SELECT issue 
         FROM dataissue, issue 
         WHERE dataissue.issue = issue.id 
           AND value = 'Fermée' 
           AND substring(issue.entry,1,3) = 'ema' 
 ) 

 AND issue IN (
         SELECT issue 
         FROM   dataissue, issue 
         WHERE  dataissue.issue = issue.id 
         AND    field = 'version(s)_corrigée(s)' AS b 
         AND    substring(issue.entry,1,3) = 'ema' 
 ) 

GROUP BY dataissue.value as b

要sumarize:该组使用主查询value alias a中的字段WHERE field = 'point_d_effort'。但是,我想在嵌套查询( value alias b )内的字段WHERE field = 'Version(s)_corrigée(s)'进行分组。

我该怎么做?谢谢。

为了更精确,

大家好,首先,我要感谢您为答案做出贡献,这是一个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)'  

1 个答案:

答案 0 :(得分:1)

SELECT  main2.value AS VALUE,nbreticket,ticket FROM 
(
SELECT dataissue.issue,dataissue.value,COUNT(VALUE) AS nbreticket,SUM(VALUE) AS ticket,SUBSTRING(issue.entry,1,3) ,FIELD
FROM DataIssue,issue WHERE  dataissue.issue = issue.id  AND VALUE IS NOT NULL AND FIELD = 'point_d_effort' AND issue IN ( SELECT issue
FROM dataissue,issue WHERE dataissue.issue = issue.id AND VALUE = 'récit' 
AND SUBSTRING(issue.entry,1,3) = 'ema' ) AND issue IN ( SELECT issue 
FROM dataissue,issue WHERE dataissue.issue = issue.id AND VALUE = 'Fermée' 
AND SUBSTRING(issue.entry,1,3) = 'ema' ) AND issue IN ( SELECT issue 
FROM dataissue,issue WHERE dataissue.issue = issue.id 
AND FIELD = 'version(s)_corrigée(s)' AND SUBSTRING(issue.entry,1,3) = 'ema' ) 
GROUP BY dataissue.value, issue

) main1 JOIN
(
SELECT  issue, `value` FROM DataIssue  WHERE  
FIELD = 'version(s)_corrigée(s)' 

)main2
WHERE main1.issue = main2.issue
GROUP BY main2.value

在你的sql GROUP BY子句中有别名,我们不能为group子句做别名。

再次在where条件有别名的地方,我们也不能为where子句做别名。

在你的sql中有一些语法错误。我清除了所有错误,现在sql正常运行。

谢谢。