sqlplus添加列标题

时间:2019-02-22 00:37:21

标签: sql oracle group-by

我正在使用来自oracle的sqlplus,并试图找出创建客户列表并将其基于以下条件进行分类的方法:

  • 如果“帐户数”为1,则将其分类为“条目级别”
  • 如果帐户数是2-3,则将其归类为“正在增长”
  • 如果帐户数大于4,则将其归类为“成熟”

然后创建一个预期的输出(我已将其附加为图片)。

expected output

我也为此附上了ERD。

这是我到目前为止所拥有的。

SELECT DISTINCT first_name "First",
                surname "Last",
                customer_number "Cust #",
                account_type "# of Accts"
  FROM (  SELECT first_name,
                 surname,
                 customer_number,
                 account_type
            FROM wgb_customer
                 JOIN wgb_account USING (customer_number)
                 JOIN wgb_account_type USING (account_type)
        ORDER BY account_type);

请帮助! 这是预期的输出!

First       Last        Cust#         # of Accts     Level
----------------------------------------------------------------        
Peter      Chen         2566217             3         Growing           
Byron      Griffith     1113004             1         Entry Level
Patricia   Lee          9871332             1         Entry Level
Henri      Poincare     1113501             3         Growing   
John       Synge        1112401             2         Growing   

1 个答案:

答案 0 :(得分:0)

这听起来像带有case表达式的聚合:

select c.first_name, c.surname, c.customer_number,
       count(*) as num_accounts,
       (case when count(*) = 1 then 'Entry Level'
             when count(*) <= 3 then 'Growing'
             else 'Mature'
        end) as level
from wgb_customer c join
     wgb_account a
     using (customer_number) 
group by c.first_name, c.surname, c.customer_number;