Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a GROUP BY like table?

Animal Count  Color
------ -----  -----
Dog      2     brown
Cat      4     black

Result 

Animal  Color
------  
Dog     brown
Dog     brown
Cat     black
Cat     black
Cat     black
Cat     black
like image 529
Subin Jacob Avatar asked Feb 10 '23 10:02

Subin Jacob


2 Answers

You can achieve It with Common Table Expression in following:

CREATE TABLE #Test
(
   Animal NVARCHAR(20),
   CountAnimals INT,
   Color NVARCHAR(20)
)

INSERT INTO #Test VALUES ('Dog', 2, 'brown'), ('Cat', 4, 'black');

WITH CTE AS (
    SELECT Animal,CountAnimals,Color FROM #Test

    UNION ALL 

    SELECT  Animal,CountAnimals-1,Color

    FROM CTE
    WHERE CountAnimals >= 2
)
SELECT Animal,Color
FROM CTE
ORDER BY Animal DESC
OPTION (MAXRECURSION 0);

DROP TABLE #Test

OUTPUT

Animal  Color
 Dog    brown
 Dog    brown
 Cat    black
 Cat    black
 Cat    black
 Cat    black

SQL FIDDLE

like image 193
Stanislovas Kalašnikovas Avatar answered Feb 13 '23 02:02

Stanislovas Kalašnikovas


You need to introduce an artificial table (or view) the_row_holder_table with row count>=max count in the initial table. Then just

select gr.Animal, gr.Color
from grouped gr 
join the_row_holder_table on gr.count<the_row_holder_table.row

UPDATE: Suppose the the_row_holder_table has just one column row with values

row
-----
1
2
3
...

Then each row of the grouped table is connected (by gr.countcount rows of the the_row_holder_table table

like image 36
StanislavL Avatar answered Feb 13 '23 00:02

StanislavL