gpt4 book ai didi

sql - 如何反转像表一样的 GROUP BY?

转载 作者:行者123 更新时间:2023-12-04 19:58:31 25 4
gpt4 key购买 nike

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

Result

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

最佳答案

您可以通过 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

关于sql - 如何反转像表一样的 GROUP BY?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29645733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com