集团通过澄清

时间:2017-06-20 10:11:07

标签: mysql

这就是我想要的东西(用想象的sql编写):

SELECT A, B, C, AVG(  `Value` ) AS Value
FROM T 
GROUP BY A, B, C
HAVING AT LEAST TWO DIFFRENT C VALUES PER DISTINCT A,B 
ORDER BY A, B, C

是否可以在适当的mysql中重写这样的HAVING条件?

在First,我认为这会奏效:

    SELECT A, B, C, AVG(  `Value` ) AS Value
    FROM T 
    GROUP BY A, B, C
    HAVING COUNT(C)>2
    ORDER BY A, B, C

但它并不是因为对于相同的A,B,C组合不可能有2个不同的C值,所以你会怎么做?

2 个答案:

答案 0 :(得分:2)

您可以将查询分为两个不同的查询:

  1. 每个不同的A,B至少有两个不同的C值

    select A, B
    from T
    group by A, B
    having count(DISTINCT C)>1
    
  2. 您的最终查询

    select  A, B, C, avg(Value)
    from T
    where
      (A, B) in (
        select A, B
        from T
        group by A, B
        having count(DISTINCT C)>1
      )
    group by
      A, B, C
    

答案 1 :(得分:1)

您可以尝试使用 WHERE 语句而不是 HAVING

SELECT A, B, C, AVG(  `Value` ) AS Value
FROM T 
WHERE 
     (
     SELECT COUNT(DISTINCT C)
     FROM T1
     WHERE T1.A = T.A AND T1.B = T.B
     ) >= 2
GROUP BY A, B, C
ORDER BY A, B, C