我有一个像这样的SQL表
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
...
如何运行查询来更改表格,使其如下所示:
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
...
谢谢!
答案 0 :(得分:0)
我认为你需要两个级别的聚合:
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;