Answer the question
In order to leave comments, you need to log in
How to explain the logic of the following SQL query?
The query is as follows:
with tbl as
(
select [Week], Client
from (values (1, 'a'),
(1, 'b'),
(1, 'c'),
(2, 'f'),
(2 , 'a'),
(3, 'q'),
(3, 'y'),
(3, 'c')) as tbl ([Week], Client)
)
select tbl.[Week], count(distinct t1.Client)
from tbl
inner join tbl t1
on tbl.[Week] >= t1.[Week]
group by tbl.[Week] The
query returns unique values as a cumulative total.
But I can’t understand the logic of its execution, especially with inner join (it’s not necessary to explain how inner join works).
Can someone describe in detail what the request does?
Answer the question
In order to leave comments, you need to log in
In a nutshell, this is a week-by-week growth trend for unique customers. Google - "Current total". In fact, by the first week, records for the first week are joined, by the second - for the first and second, and so on. according to the condition tbl.[Week] >= t1.[Week]
Each client joins with clients of the current and previous week. So in 1 week there will be 9 clients! Then grouped by tbl.Week to get unique weeks. For each week, the aggregation of customers is the sum of unique customers. By counting uniques, the first join is corrected and we get 3 clients instead of 9
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question