в SQL создать флаг по одной переменной за 6 месяцев - PullRequest
0 голосов
/ 20 февраля 2019

Я хочу извлечь матрицу из таблицы 'CARAT_AGG'.где BILLLING_ACCOUNT_ID - это мой первичный ключ (CUSTOMER COUNT).Я хочу, чтобы все DISTINCT BILLLING_ACCOUNT_ID, чей CUSTOMER_STATUS был «ACTIVE», были помечены как 1, а CUSTOMER_STATUS как «ноль», были помечены как 0 в течение месяца.а затем создайте итоговое суммирование столбцов всех 6 столбцов с 1 или 0.

Я написал приведенный ниже запрос, кто-то может помочь.output should look like this

select DISTINCT MONTH_YEAR, count(BILLING_ACCOUNT_ID), 

sum(case when month_year = '01-APR-18' then NVL(CUSTOMER_STATUS,0) else 1 end)  over (partition by MONTH_YEAR) APR_STATUS,
sum(case when month_year = '01-MAY-18' then NVL(CUSTOMER_STATUS,0) else 1 end)  over (partition by MONTH_YEAR) MAY_STATUS,
sum(case when month_year = '01-JUN-18' then NVL(CUSTOMER_STATUS,0) else 1 end)  over (partition by MONTH_YEAR) JUN_STATUS,
sum(case when month_year = '01-JUL-18' then NVL(CUSTOMER_STATUS,0) else 1 end)  over (partition by MONTH_YEAR) JUL_STATUS,
sum(case when month_year = '01-AUG-18' then NVL(CUSTOMER_STATUS,0) else 1 end)  over (partition by MONTH_YEAR) AUG_STATUS,
sum(case when month_year = '01-SEP-18' then NVL(CUSTOMER_STATUS,0) else 1 end)  over (partition by MONTH_YEAR) SEP_STATUS
from CARAT_AGG 
group by MONTH_YEAR
order by MONTH_YEAR
;

1 Ответ

0 голосов
/ 20 февраля 2019

Вы можете написать это как:

select BILLING_ACCOUNT_ID, 
       sum(case when month_year = date '2018-04-01' and customer_status = 'ACTIVE' then 1 else 0 end) as APR_STATUS,
       sum(case when month_year = date '2018-05-01' and customer_status = 'ACTIVE' then 1 else 0 end) as MAY_STATUS,
       sum(case when month_year = date '2018-06-01' and customer_status = 'ACTIVE' then 1 else 0 end) as JUN_STATUS,
       sum(case when month_year = date '2018-07-01' and customer_status = 'ACTIVE' then 1 else 0 end) as JUL_STATUS,
       sum(case when month_year = date '2018-08-01' and customer_status = 'ACTIVE' then 1 else 0 end) as AUG_STATUS,
       sum(case when month_year = date '2018-09-01' and customer_status = 'ACTIVE' then 1 else 0 end) as SEP_STATUS,
       sum(case when month_year in (date '2018-04-01', date '2018-05-01', date '2018-06-01', date '2018-07-01', date '2018-08-01', date '2018-09-01') and customer_status = 'ACTIVE' then 1 else 0 end) as total
from CARAT_AGG 
group by BILLING_ACCOUNT_ID
order by BILLING_ACCOUNT_ID
;

Примечания:

  • У Oracle есть хороший синтаксис для констант даты - с использованием ключевого слова date (это на самом деле стандартSQL).
  • Вы хотите одну строку на BILLING_ACCOUNT_ID, чтобы это было ваше предложение GROUP BY.
  • Вы хотите проверить активный статус, так что сделайте это явно.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...