I have a sql table like this
saledate | user_id | Purchase or Return | trans_amount
2016/4/1 | 001 | Purchase | 100
2016/4/1 | 001 | Return | 200
2016/4/2 | 002 | Purchase | 300
2016/4/2 | 003 | Purchase | 200
2016/4/2 | 004 | Return | 100
...
How can I run a query to change the table so that it looks like this:
saledate | transaction_type | number of unique user_ids | total_amount
2016/4/1 | Purchase only | 20 | 1000
2016/4/1 | Return only | 30 | 1000
2016/4/1 | Purchase_return | 40 | 2000
...
Thank you!
You are going to need two levels of aggregation, I think:
select salesdate, transaction_type,
count(*) as NumUsers, sum(amount) as total_amount
from (select user_id, salesdate,
(case when max(PurchaseOrReturn) = min(PurchaseOrReturn)
then max(PurchaseOrReturn) else 'Both'
end) as transaction_type,
sum(trans_amount) as amount
from t
group by user_id, salesdate
) t
group by salesdate, transaction_type
order by salesdate, transaction_type;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.