Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

mysql - need to return two sets of data with two different where clauses

I have a table that keeps track of transactions.

The table is setup as:

transactions:

id, account_id, budget_id, points, type

I need to return each budget_id's sum of points where type = 'allocation' and sum of points where type = 'issue'

I know how to do each, but not both in one query.

expected result set:

budget_id   allocated   issued
   434       200000      100
   242       100000      5020
   621       45000       3940
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
SELECT budget_id, 
       SUM(IF(type = 'allocation', points, 0)) AS allocated,
       SUM(IF(type = 'issue', points, 0)) AS issued
FROM transactions
GROUP BY budget_id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...