[英]how to use case with condition in 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_id
為2
,如果未顯示為0.00,則計算pending
總數; 如何為此編寫查詢?
樣本選擇查詢:
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
預期輸出:如果Manager 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
試試這個:
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
試試這個
SELECT CASE user.manager_id何時2 THEN SUM(pending)ELSE 0 END asending_total FROM ... WHERE ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.