Unlock a world of possibilities! Login now and discover the exclusive benefits awaiting you.
Здравствуйте,
Использую Qlik Sense. Уровень у меня - самый начальный, разбираюсь с азами.
Есть задача: рассчитать количество новых покупателей.
В модели данных, есть календарь. Так же, есть поле с уникальными ID клиента, которые добавляются ежедневно, по мере поступления новых заказов.
Если производить выборку "distinct ID", например за конкретную дату, то я соответственно получаю все ID уникальными, если конечно, клиент не сделал повторный заказ в этот же день.
Мне необходимо сравнить уникальных покупателей за выбранный период, со всеми уже имеющимися, что бы получить количество абсолютно новых, не делавших заказ ранее.
Подскажите пожалуйста, как можно реализовать данную задачу? Не обязательно такой же логикой.
Script for Sample data you provided <MODIFIED SCRIPT>
FACT:
LOAD person_jd,
order_date,
NUM(Month(order_date)) as OrderMonth,
Year(order_date) as OrderYear,
AutoNumber(person_jd&order_date,person_jd) as OrderNum_ByCustomer,
OrderYear&if(len(NUM(Month(order_date)))=1,0&NUM(Month(order_date)),NUM(Month(order_date))) as Order_YrMonth
FROM
(
//end of Script//
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
New Customers between Selected Months
Expression :
count({<OrderNum_ByCustomer = {1}
,OrderMonth = {'>=$(vMonthFrom)<=$(vMonthTo)'}
,OrderYear = {$(vYear)}
>}OrderNum_ByCustomer)
Existing Customers between Selected Months
count({<OrderNum_ByCustomer = {'>1'}
,OrderMonth = {'>=$(vMonthFrom)<=$(vMonthTo)'}
,OrderYear = {$(vYear)}
>}OrderNum_ByCustomer)
Input Variables used
LOGIC
count({<Period= {PeriodSelected} , ID = e({<Period= {'<PeriodSelected'}>}ID)>}DISTINCT ID)
Somewhat Similar to this
It'll be easier to demonstrate if you post sample/dummy data
Александр, добрый вечер!
Попробуйте эту формулу
sum(aggr(if(monthstart(min(Total <[ID Клиента]> Дата))= МесГод,1,0),[ID Клиента],МесГод))
где МесГод создан в скрипте так:
Date( Monthstart (Дата), 'MMM-YYYY') AS МесГод,
либо используйте YearMonth, созданный автоматически при загрузке через Data Manager.
Доброго дня, Анна.
Благодарю, за ответ.
При подстановке дат, данная формула возвращает мне значение, аналогичное count (distinct ([id_клиента]).
Это уникальные клиенты текущей выборки, то есть, одного дня.
Для примера, взято 18.02.2015.
Но как видно из поля id_клиента, в этот день у нас было всего 4 новых, не делавших заказ ранее. Об этом говорит разрыв записи между 31646 и 31670. Начиная с 31670 и заканчивая 31673 - это абсолютно новые клиенты, сделавшие свой первый заказ 18.02.2015
sum(aggr(if(monthstart(Min(Total<[id_клиента]> [дата_заказа]))=[МесяцГод],1,0),[id_клиента],[МесяцГод]))
Правильно ли я подставляю значения дат в формулу?
Код_календаря:
QuartersMap:
MAPPING LOAD
rowno() as Month,
'Q' & Ceil (rowno()/3) as Quarter
AUTOGENERATE (12);
Temp:
Load
min([дата_заказа]) as minDate,
max([дата_заказа]) as maxDate
Resident [ИнформацияЗаказа];
Let varMinDate = Num(Peek('minDate', 0, 'Temp'));
Let varMaxDate = Num(Peek('maxDate', 0, 'Temp'));
DROP Table Temp;
TempCalendar:
LOAD
$(varMinDate) + Iterno()-1 As Num,
Date($(varMinDate) + IterNo() - 1) as TempDate
AutoGenerate 1 While $(varMinDate) + IterNo() -1 <= $(varMaxDate);
[Календарь]:
Load
date(TempDate, 'DD.MM.YY') AS [дата_заказа],
Week(weekstart(TempDate)) & '-' & WeekYear(TempDate) as Неделя,
Year(TempDate) As [Год],
date(MonthStart(TempDate),'MMM') As [Месяц],
Dual(Month(TempDate)&'-'&Year(TempDate), MonthStart(TempDate)) as МесяцГод,
ApplyMap('QuartersMap', month(TempDate), Null())&' - '& year(TempDate) as [Квартал]
Resident TempCalendar
Order By TempDate asc;
Drop Table TempCalendar;
Вот модель данных:
Vineeth Pujari, Hello
Thank you for your reply.
If possible, could you explain in more detail what must be specified in the "period" and "PeriodSelected"? Or give a link to the manual qlik where I can study the operating principle of this formula.
Hi Alexander,
Please post some dummy data in Excel so I can demonstrate how to achieve the desired result.
Добрый день.
На уровне скрипта пронумеруйте заказы по каждому клиенту, и используйте это поле для фильтрации.
count({<ПорядковыйНомер={'1'}>} [ID Клиента])
Vineeth , Hi !
I take the data from MySQL. Download to Excel main fields associated with the current issue. In 2001, data transfer, it does not consider. The logic is this: when a customer buys the first time, he was assigned to "id_customer". To one customer_id can belong to several different person_id. This can be a husband or wife. To order specified person ID. Through it, we identify the customer. The client is the same, different person.
When we meet a unique customer_id the first time, this is the date of the first order. If I make a selection on a particular date, then the day all the customer_id unique and not repeated. But some may have already bought something earlier. I need to compare the current selection customer_id with the rest of the database for all the time. Then I find out what made the order for the first time and which have placed before.
Здравствуйте, Евгений.
Спасибо за ответ. Попробую реализовать такой вариант. Думаю, он сработает.
Данные выгружаются из БД MySQL и консолидируются уже в модели по идентификаторам из разных связанных таблиц. Клиенты отдельно, заказы отдельно.
Как я понимаю, на уровне скрипта загрузки, мне потребуется собрать их в некую общую таблицу, а там уже нумеровать по дополнительному полю?
Привет,
Да, надо будет в одной таблице иметь сведения по заказу (дата, клиент)