Skip to main content
Announcements
Live today at 11 AM ET. Get your questions about Qlik Connect answered, or just listen in. SIGN UP NOW
cancel
Showing results for 
Search instead for 
Did you mean: 
alexander_zelen
Contributor
Contributor

Расчет количества новых покупателей

Здравствуйте,

Использую Qlik Sense. Уровень у меня - самый начальный, разбираюсь с азами.

Есть задача: рассчитать количество новых покупателей.

В модели данных, есть календарь. Так же, есть поле с уникальными ID клиента, которые добавляются ежедневно, по мере поступления новых заказов.

Если производить выборку "distinct ID", например за конкретную дату, то я соответственно получаю все ID уникальными, если конечно, клиент не сделал повторный заказ в этот же день.

Мне необходимо сравнить уникальных покупателей за выбранный период, со всеми уже имеющимися, что бы получить количество абсолютно новых, не делавших заказ ранее.

Подскажите пожалуйста, как можно реализовать данную задачу? Не обязательно такой же логикой.

1 Solution

Accepted Solutions
vinieme12
Champion III
Champion III

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


(
ooxml, embedded labels, table is information_about_order);

//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

241141.PNG

Vineeth Pujari
If a post helps to resolve your issue, please accept it as a Solution.

View solution in original post

15 Replies
vinieme12
Champion III
Champion III

LOGIC

count({<Period= {PeriodSelected} , ID = e({<Period= {'<PeriodSelected'}>}ID)>}DISTINCT  ID)


Somewhat Similar to this

Expression to get List1\List2

It'll be easier to demonstrate if you post sample/dummy data

Vineeth Pujari
If a post helps to resolve your issue, please accept it as a Solution.
Anna_Klimkova
Employee
Employee

 

Александр, добрый вечер!

Попробуйте эту формулу

sum(aggr(if(monthstart(min(Total <[ID Клиента]> Дата))= МесГод,1,0),[ID Клиента],МесГод))

где МесГод создан в скрипте так:

Date( Monthstart (Дата), 'MMM-YYYY') AS МесГод,

либо используйте YearMonth, созданный автоматически при загрузке через Data Manager.

 

alexander_zelen
Contributor
Contributor
Author

Доброго дня, Анна.

Благодарю, за ответ.

При подстановке дат, данная формула возвращает мне значение, аналогичное 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_клиента],[МесяцГод]))

Правильно ли я подставляю значения дат в формулу?

Screen1.PNG

Код_календаря:

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;

Вот модель данных:

Screen2.PNG

alexander_zelen
Contributor
Contributor
Author

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.

vinieme12
Champion III
Champion III

Hi Alexander,

Please post some dummy data in Excel so I can demonstrate how to achieve the desired result.

Vineeth Pujari
If a post helps to resolve your issue, please accept it as a Solution.
Eugeny_Ilyin
Creator II
Creator II

Добрый день.

На уровне скрипта пронумеруйте заказы по каждому клиенту, и используйте это поле для фильтрации.

count({<ПорядковыйНомер={'1'}>} [ID Клиента])

alexander_zelen
Contributor
Contributor
Author

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.

alexander_zelen
Contributor
Contributor
Author

Здравствуйте, Евгений.

Спасибо за ответ. Попробую реализовать такой вариант. Думаю, он сработает.

Данные выгружаются из БД MySQL и консолидируются уже в модели по идентификаторам из разных связанных таблиц. Клиенты отдельно, заказы отдельно.

Как я понимаю, на уровне скрипта загрузки, мне потребуется собрать их в некую общую таблицу, а там уже нумеровать по дополнительному полю?

Eugeny_Ilyin
Creator II
Creator II

Привет,

Да, надо будет в одной таблице иметь сведения по заказу (дата, клиент)