如何像表一样反转GROUP BY?

时间:2015-04-15 08:50:39

标签: sql sql-server-2008

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

Result 

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

5 个答案:

答案 0 :(得分:6)

您可以使用以下Common Table Expression来实现它:

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

<强>输出

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

<强> SQL FIDDLE

答案 1 :(得分:2)

您需要在初始表中引入一个人工表(或视图)the_row_holder_table,行数> gt = = max count。然后只是

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

更新: 假设the_row_holder_table只有一列row,其值为

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

然后连接分组表的每一行(通过the_row_holder_table表的gr.countcount行

答案 2 :(得分:1)

你可以这样做:

测试数据:

DECLARE @tbl TABLE(Animal varchar(100), Count INT, Color VARCHAR(100))
INSERT INTO @tbl
VALUES
    ('Dog',2,'brown'),
    ('Cat',4,'black')

使用递归cte + cross apply。你可以这样做:

DECLARE @max INT=(SELECT MAX(Count) FROM @tbl);
;WITH Nbrs ( n ) AS (
        SELECT 1 UNION ALL
        SELECT 1 + n FROM Nbrs WHERE n < @max )
SELECT 
    t.Animal,
    t.Count,
    t.Color 
FROM 
    @tbl as t 
    CROSS APPLY 
    (
        SELECT * FROM Nbrs WHERE Nbrs.n<=t.Count
    ) AS f
ORDER BY t.Animal DESC

<强>输出

Dog 2   brown
Dog 2   brown
Cat 4   black
Cat 4   black
Cat 4   black
Cat 4   black

答案 3 :(得分:0)

declare @ints table(ID int)
declare @animals table(animal varchar(20),[count] int,color varchar(20))
insert into @animals values ('Dog',      2     ,'brown'),('Cat',      4     ,'black')

declare @int int = 1
declare @maxInt int = (SELECT MAX([count]) from @animals)
while @int <= @maxInt 
BEGIN
    INSERT INTO 
        @ints
    VALUES
        (@int)

    SET @int = @int + 1
END


SELECT
    animal,
    color
FROM
    @animals a
    INNER JOIN @ints i ON i.ID <=a.[count]
ORDER BY
    animal ASC

答案 4 :(得分:-1)

WITH CTE AS (

SELECT animal,count,color FROM tes

UNION ALL 

SELECT  animal,count-1,color

FROM CTE
WHERE count > 1
 )

SELECT animal,color
FROM CTE
group by animal,color