Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip/repeat join?

Tags:

sql

tsql

Let's say I have a simple table of documents with a type column:

Documents
Id  Type
1   A
2   A
3   B
4   C
5   C
6   A
7   A
8   A
9   B
10  C

Users have permissions to access different types of documents:

Permissions
Type    User
A       John
A       Jane
B       Sarah
C       Peter
C       John
C       Mark

And I need to distribute those documents among the users as tasks:

Tasks
Id  T DocId UserId
1   A   1   John
2   A   2   Jane
3   B   3   Sarah
4   C   4   Peter
5   C   5   John
6   A   6   John
7   A   7   Jane
8   A   8   John
9   B   9   Sarah
10  C   10  Mark

How do I do that? How do I get the Tasks?

like image 638
Yegor Avatar asked Oct 30 '16 13:10

Yegor


People also ask

What does zip (*) do in Python?

Python's zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.

What happens if you zip two lists of different lengths?

Answer. The zip() function will only iterate over the smallest list passed. If given lists of different lengths, the resulting combination will only be as long as the smallest list passed.

Can you zip a list of lists?

We can combine the list of lists using the zip() method.


1 Answers

You can enumerate the rows and then use modulo arithmetic for the matching:

with d as (
      select d.*,
             row_number() over (partition by type order by newid()) as seqnum,
             count(*) over (partition by type) as cnt
      from documents d
     ),
      u as (
       select u.*,
              row_number() over (partition by type order by newid()) as seqnum,
              count(*) over (partition by type) as cnt
       from users u
      )
select d.*
from d join
     u
     on d.type = u.type and
        u.seqnum = (d.seqnum % u.cnt) + 1
like image 67
Gordon Linoff Avatar answered Oct 03 '22 16:10

Gordon Linoff