sql notes: hackerrank draw the triangle 2

Problem


P(R) represents a pattern drawn by Julia in R rows. The following pattern represents P(5):

*
* *
* * *
* * * *
* * * * *

Write a query to print the pattern P(20).

Analysis


For this problem, use REPEAT function to generate texts of each line. Also, use a variable to decide the length of each line and apply REPEAT functon for each row of a table with at least 20 rows. Finally, control the number of lines to output.

First, declare and initialize a variable:

1
SET @number = 0;

Then, choose a table with at least 20 rows and apply REPEAT function for each row. Also, increase the variable by 1 each time before applying the function:

1
2
SET @number = 0;
SELECT REPEAT('* ', @number := @number+1) FROM information_schema.tables;

Finally, output the first 20 lines:

1
2
SET @number = 0;
SELECT REPEAT('* ', @number := @number+1) FROM information_schema.tables LIMIT 20;

Or

1
2
SET @number = 0;
SELECT REPEAT('* ', @number := @number+1) FROM information_schema.tables WHERE @number < 20;

Solution


Solution 1

1
2
SET @number = 0;
SELECT REPEAT('* ', @number := @number+1) FROM information_schema.tables LIMIT 20;

Solution 2

1
2
SET @number = 0;
SELECT REPEAT('* ', @number := @number+1) FROM information_schema.tables WHERE @number < 20;

Draw The Triangle 2
(中文版) SQL 笔记: Hackerrank Draw The Triangle 2