单个Statement中有多个COUNT和GROUP BY

时间:2016-10-12 06:24:12

标签: php mysql json

我在单个语句中使用DISTINCT,LEFT JOIN,COUNT和GROUP BY,如下所示:

SELECT * 
FROM Emp_det
JOIN table_1 ON CompoffEntry.employee_detail_id = Emp_det.employee_detail_id
WHERE Emp_det.emp_status = "A" 
AND 'Emp_det.department_id = '.$department : ''
AND ($roleId == 5) ? 'reporting_id = '.$user_id : ''

编码的JSON看起来像这样:

SELECT distinct r.sid as sid, s.name as sname, s.image as simage, 
COUNT(r.sid) as scount FROM batch_request r LEFT JOIN student_info s ON s.id = r.sid 
WHERE r.tid='22' group by r.sid

表:

{{3}}

正如您在上面的图片中看到的,我在一个表中总共有6条记录(3表示sid = 1,3表示sid = 2)

sid 1记录的状态(2确认[其中值为1]和1拒绝[其中值为2]),以相同的方式为sid 2记录的状态(1确认[其中值为1]和2拒绝[其中值为2])

同样的事情我想通过我上面发布的QUERY来将数据编码为JSON,正如你所看到的,我仍然为两个JSON对象获取null(即:确认和拒绝)

问题1 <{1}}和{ "students": [ { "sid":"1", "sname":"Sonali Kohli", "simage":"22", "scount":"3", "sconfirmed":null, "sdeclined":null }, { "sid":"2", "sname":"Sona Ali Khan", "simage":"22", "scount":"3", "sconfirmed":null, "sdeclined":null } ],"success":1 } 对于 < strong> JSON ?

答案1:如果sconfirmed sconfirmed = 2且 sdeclined = 1)和{{1} }( sconfirmed = 1且 sdeclined = 2)

问题2:数据库表中的sdeclinedsid = 1是什么?

答案2: sid = 2只是记录的计数,其中状态sconfirmed特定< strong> sid 和sdeclined是记录的计数,其中状态sconfirmed特定 sid

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

SELECT distinct r.sid as sid, s.name as sname, s.image as simage, COUNT(r.sid) as scount, 
SUM(CASE r.status WHEN 1 THEN 1 ELSE 0 END) as sconfirmed, 
SUM(CASE r.status WHEN 2 THEN 1 ELSE 0 END) as sdeclined, 
SUM(CASE r.status WHEN 0 THEN 1 ELSE 0 END) as spending  
FROM batch_request r LEFT JOIN student_info s ON s.id = r.sid 
WHERE r.tid='22' 
GROUP BY r.sid