SQL选择总和计数多次,单独使用值

时间:2015-05-26 12:40:33

标签: sql

我试图使用不同的“where”值将同一列的计数拉三次。 例如

public function indexAction()
{
    $em = $this->getDoctrine()->getManager();
    $user = $this->getUser();
    $entities = $em
        ->getRepository('BreedrGeckoBundle:Weight')
        ->findBy(array('user' => $user), array());

    return array(
        'entities' => $entities,
    );
}

预期

SELECT (sum(count(phonenum) FROM table1 WHERE uniqueID IN ( 123, 43, 124, 44, 112)) AS blabla_LTD)
    ,(sum(count(phonenum) FROM table1 WHERE uniqueID IN (163, 53, 114, 45, 222)) AS lablab_LTD)

感谢您的协助。

2 个答案:

答案 0 :(得分:3)

您可以使用子查询,但我认为条件聚合可能更有效:

select sum(case when uniqueID IN ( 123, 43, 124, 44, 112)
                then 1 else 0
           end) AS blabla_LTD,
       sum(case when uniqueID IN (163, 53, 114, 45, 222)
                then 1 else 0
           end) AS lablab_LTD
from table1 
where phonenum is not null;

如果您在uniqueId上有索引,那么在ids子句中包含所有where也可能有助于提高效果:

where uniqueId in (123, 43, 124, 44, 112, 163, 53, 114, 45, 222)

答案 1 :(得分:1)

我认为这会为你做到:

SELECT 
    SUM(CASE WHEN uniqueID IN ( 123, 43, 124, 44, 112) AND phoneNum IS NOT NULL THEN 1 ELSE 0 END)
    , SUM(CASE WHEN uniqueID IN (163, 53, 114, 45, 222) AND phoneNum IS NOT NULL THEN 1 ELSE 0 END)
FROM table1