Php 如何在mysql中使用带条件的用例
使用mysql查询如何在类似(Php 如何在mysql中使用带条件的用例,php,mysql,Php,Mysql,使用mysql查询如何在类似(manager\u id=2)的条件下使用case 我有三张带柱的桌子 user - id - name - dept - manager_id itemone - id - detail - status - amount - created_by itemtwo - id - detail - status - amount - created_by 基于状态列,可以找到草稿、待决、已批准和已拒绝 当我的manager\u id为2
manager\u id=2
)的条件下使用case
我有三张带柱的桌子
user
- id
- name
- dept
- manager_id
itemone
- id
- detail
- status
- amount
- created_by
itemtwo
- id
- detail
- status
- amount
- created_by
基于状态
列,可以找到草稿、待决、已批准和已拒绝
当我的manager\u id
为2
时,如果不是,则计算待定的总计
显示为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;
在中查找表架构
获得以下结果
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
试试这个
选择CASE user.manager\u id(当2时),然后求和(挂起)否则0结束为挂起\u总计
从…起
其中…尝试以下方法:
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
我需要一些东西,比如2时的user.manager\u id和2时的status,然后求和(待定)