简体   繁体   English

SQL根据内容创建一个新列

[英]SQL create a new column based on the contents

I have a sql table like this 我有一个像这样的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
...

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM