带有条件的DQL

时间:2015-07-01 10:15:54

标签: mysql doctrine dql

我有这样的DQL:

$dql = "SELECT d.name, "
. "SUM(m.id and m.status = 'a') members, "
. "SUM(m.position_id = 19 and m.status = 'a') subcon, "
. "SUM(m.position_id = 20 and m.status = 'a') ojt, "
. "SUM(m.status = 'h') hr_intra "
. "FROM OssOrgBundle:User m "
. "RIGHT JOIN OssOrgBundle:Department d "
. "ON m.department = d.id "
. "GROUP BY d.id";

$qb = $em->createQuery($dql);
deptListCount = $qb->getResult();

doctrine是否支持聚合函数SUM及其中的条件? 我在SQL中尝试了查询,它可以工作。 我无法将其转换为DQL

我也是这样做的:

$deptListCount = $em->createQueryBuilder("r")
->select("d.name")
->addSelect("SUM(m.id AND m.status = 'a') members")
->addSelect("SUM(m.position_id = 19 and m.status = 'a') subcon")
->addSelect("SUM(m.position_id = 20 and m.status = 'a') ojt")
->addSelect("SUM(m.status = 'h') hr_intra ")
->from("OssOrgBundle:Department", "d")
->leftJoin("OssOrgBundle:User", "m", "WITH", "m.deprtment = :id")
->groupBy("d.id")
->getQuery()
->getResult(AbstractQuery::HYDRATE_ARRAY);

仍然无法正常工作

1 个答案:

答案 0 :(得分:1)

否则您需要将case when用于条件sum

sum( case when m.position_id = 19 and m.status = 'a' then 1 else 0 end ) as subcon

在DQL中更改其余部分以及

m.id AND m.status = 'a'不确定您尝试应用的逻辑我假设您正在寻找某些内容

sum( case when m.id is not null and m.status = 'a' then 1 else 0 end ) as members