T
T
Temp_admin2016-06-29 13:09:14
SQL
Temp_admin, 2016-06-29 13:09:14

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

2 answer(s)
D
Dmitry Kovalsky, 2016-06-29
@Temp_admin

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]

V
Vladimir Shestakov, 2016-06-29
@boolive

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 question

Ask a Question

731 491 924 answers to any question