如何在mysql中使用带有条件的case

时间:2015-12-10 09:59:37

标签: php mysql

使用mysql查询如何使用case条件(manager_id=2)。

我有三个表格列

user
 - id
 - name
 - dept
 - manager_id
itemone
 - id
 - detail
 - status
 - amount
 - created_by
itemtwo
 - id
 - detail
 - status
 - amount
 - created_by

基于status列能够找到草稿,待处理,已批准和已拒绝

  

当我的manager_id2时,如果没有,则计算pending的总数   显示为0.00;如何为此编写查询?

示例选择查询:

SELECT t1.name, t1.dept, t1.manager_id, t2.draft_total, t2.pending_total, t2.approved_total, t2.rejected_total FROM user t1, 
(
    SELECT uat.created_by, SUM(uat.amount) AS total, SUM(uat.draft) AS draft_total, SUM(uat.pending) AS pending_total, SUM(uat.approved) AS approved_total, SUM(uat.rejected) AS rejected_total FROM 
    (
        SELECT id, detail, status, amount, CASE status WHEN 1 THEN amount ELSE 0 END AS draft, CASE status WHEN 2 THEN amount ELSE 0 END AS pending, CASE status WHEN 3 THEN amount ELSE 0 END AS approved, CASE status WHEN 4 THEN amount ELSE 0 END AS rejected,created_by FROM itemone UNION ALL SELECT id, detail, status, amount, CASE status WHEN 1 THEN amount ELSE 0 END AS draft, CASE status WHEN 2 THEN amount ELSE 0 END AS pending, CASE status WHEN 3 THEN amount ELSE 0 END AS approved, CASE status WHEN 4 THEN amount ELSE 0 END AS rejected,created_by FROM itemtwo
    ) 
    uat GROUP BY uat.created_by
) t2 WHERE t1.id=t2.created_by ORDER BY name ASC;

SQLFiddle

中查找表架构

获得以下结果

 name       | dept  | manager_id    | draft_total   | pending_total | approved_total    | rejected_total
user four   | Y     | 2             | 79.75         | 54.10         | 90.30             | 100.20  
user one    | X     | 1             | 79.75         | 54.10         | 90.30             | 100.20
user two    | X     | 1             | 84.25         | 0.00          | 0.00              | 0.00

期望输出:如果经理ID为2,则结果应为

name        | dept  | manager_id    | draft_total   | pending_total | approved_total    | rejected_total
user four   | Y     | 2             | 79.75         | 54.10         | 90.30             | 100.20  
user one    | X     | 1             | 79.75         | 0.00          | 90.30             | 100.20
user two    | X     | 1             | 84.25         | 0.00          | 0.00              | 0.00

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT t1.name, t1.dept, t1.manager_id,
sum(case when t2.status=1 then t2.amount else 0 end) AS draft_total, 
sum(case when t2.status=2 and t1.manager_id=2  then t2.amount else 0 end) AS pending_total, 
sum(case when t2.status=2 then t2.amount else 0 end) AS approved_total, 
sum(case when t2.status=4 then t2.amount else 0 end) AS rejected_total
FROM user t1
inner join (
  select * from itemone
  union all 
  select * from itemtwo
) t2 on t1.id=t2.created_by 
group by t1.id
ORDER BY t1.name ASC

答案 1 :(得分:0)

试试这个

SELECT CASE user.manager_id WHEN 2 THEN SUM(挂起)ELSE 0 END AS pending_total 来自...... 在哪里......