W
W
wartur2015-01-29 15:23:48
SQL
wartur, 2015-01-29 15:23:48

How to make a SQL query that creates an equal number of rows from a field in a table?

I was even a little taken aback. But I would like to do this in order to make pagination by result. I understand it may not be productive, but this is the easiest at the moment.
The task is next. There is such a table

id | count | name
1  | 4     | Павел
2  | 2     | Петя
3  | 3     | Боб

As a result of some query, I would like to get the following result. The trick is to use the count field and make the number of lines equal to the number specified in this field
id | name
1  | Павел
1  | Павел
1  | Павел
1  | Павел
2  | Петя
2  | Петя
3  | Боб
3  | Боб
3  | Боб

I can join, group back and forth, I even know some functions, but such a task somehow took me aback. Maybe I don't know some function?
Thank you for your attention.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
wartur, 2015-01-30
@wartur

It appears so
There is a certain system table with identifiers 1..MAX_INT

Table "sysid"
id
1
2
3
4
...
1000
...
{MAX_INT}

Table "user"
id | count | name
1  | 4     | Павел
2  | 2     | Петя
3  | 3     | Боб

We make the following request
SELECT user.id, user.name
FROM user
LEFT JOIN sysid ON sysid.id <= user.count

Result:
id | name
1  | Павел
1  | Павел
1  | Павел
1  | Павел
2  | Петя
2  | Петя
3  | Боб
3  | Боб
3  | Боб

V
Vladimir Shestakov, 2015-01-29
@boolive

Will this do? =)))

SELECT t.* FROM table t
UNION SELECT t1.* FROM table t1 WHERE t1.count > 1
UNION SELECT t2.* FROM table t2 WHERE t2.count > 2
UNION SELECT t3.* FROM table t3 WHERE t3.count > 3
UNION SELECT t4.* FROM table t4 WHERE t4.count > 4
UNION SELECT t5.* FROM table t5 WHERE t5.count > 5
UNION SELECT t6.* FROM table t6 WHERE t6.count > 6
UNION SELECT t7.* FROM table t7 WHERE t7.count > 7
UNION SELECT t8.* FROM table t8 WHERE t8.count > 8
UNION SELECT t9.* FROM table t9 WHERE t9.count > 9

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question