尝试将两个不同的属性组合成一列

时间:2016-12-03 17:12:22

标签: sql oracle

我正在尝试编写一个显示3个不同列的查询。活动类名称,总收入和客户数量。我的下面的代码显示了这些列(以及2个不同的价格,学生和常规)。我要做的是编写一个查询,根据客户类型*适当的客户类型(学生或常规)来计算收入。我似乎无法编写查询来将2种不同的客户类型和适当的价格区分为“收入”。柱。任何帮助将不胜感激!

SELECT ACTIVITY_NAME                                          AS CLASS,
       STUDENT_PRICE,
       REGULAR_PRICE,
       Count(CUSTOMER.CUSTOMER_TYPE)                          AS NUM_CUST,
       Count(CUSTOMER.CUSTOMER_TYPE) * ACTIVITY.STUDENT_PRICE AS REVENUE
FROM   ACTIVITY
       JOIN ACTIVITY_BOOKING
         ON ACTIVITY.ID = ACTIVITY_BOOKING.ACTIVITY_ID
       JOIN CUSTOMER
         ON ACTIVITY_BOOKING.CUSTOMER_ID = CUSTOMER.ID
GROUP  BY ACTIVITY_NAME,
          STUDENT_PRICE,
          REGULAR_PRICE
ORDER  BY ACTIVITY.ACTIVITY_NAME 

1 个答案:

答案 0 :(得分:0)

我认为您需要SUM而不是COUNT,您可以将条件值汇总为:

SELECT ACTIVITY_NAME                                          AS CLASS,
       STUDENT_PRICE,
       REGULAR_PRICE,
       Count(CUSTOMER.CUSTOMER_TYPE)                          AS NUM_CUST,
       Sum (case when CUSTOMER.CUSTOMER_TYPE = 'Student' then STUDENT_PRICE when CUSTOMER.CUSTOMER_TYPE = 'Regular' then REGULAR_PRICE else 0 end) AS REVENUE
FROM   ACTIVITY
       JOIN ACTIVITY_BOOKING
         ON ACTIVITY.ID = ACTIVITY_BOOKING.ACTIVITY_ID
       JOIN CUSTOMER
         ON ACTIVITY_BOOKING.CUSTOMER_ID = CUSTOMER.ID
GROUP  BY ACTIVITY_NAME,
          STUDENT_PRICE,
          REGULAR_PRICE
ORDER  BY ACTIVITY.ACTIVITY_NAME