数据库环境:SQL SERVER 2005
现有一个需求,要枚举1-50个自然数,分10行5列展示。如图,
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAR4AAADVCAIAAAAO8whCAAARDUlEQVR4nO2dS47jyBVFtSlPtBcPPNFCvIJchSdtjwxoG16ANlCTBqp6WgLogSQyXnxvUHwfVd2DQqNaWZk8GeRl8BMv4vTHf/7LP/zDP4f/Od0N+fbjp+XmEKiEQCWQbz9+Li8YLSqNoRIIo7VBJQQqgYyjdToNIneqgWx4uC3k58zS+ZlUotJRSvdhtNZv7iSn3MA70Uo3MRvXqirexL+SUrnF4T9wVKp+l7bS0OcdpXs/Wv3v7Pwz5BvL5kh/n/J/Z2m1wtQeApWGe8heCcS4lYZ/MVZqbbT/VbDNm9HC99nwkGptePhv3uGQPUSlA5Uso7XbDfnqu9FKv3lfePoMO/E3N5d97+49RKWjlMofXt2cSyv1m26H0n14QVh+c6sVZvf08ExT3Ssg5ffu3kNUOkoJiZa90vC43ad0H14Q9qPV/7DPvjMNEubq7797Dw2VEFyU+v/AXqn84dWt2++4st2yv+9QuuNPCKc+QRg+MN33Y8uf9v4eotIhStkm1g+rJwUbpepXq/94Vul+VLSQc0O54erm8JMNQtkKO/YQlQ5R6uiVn1u2Uv9/9yndD4lW36Oz4f73gr/wrMPsHqLSUUqdn4n8FkqtBB7hs0r3gNFq7YnZgwY/Qb6p1D879veikhKOpVLMVkKO8B1K96lola3Q2h6yg6uv+aq/M/gDsx/VEpvaQx+q1D+IWwecqlJrc+W3mCmpttKdw3NTqIRAJRBGa4NKCFQCEdH69uMn//AP/xz1Z4vW9+/fTye7/xLyC7MknL79+ZfZn9PptAQja44IUAkhvpJptOI3RwSohBBfib1W9D0UASohsNcSUAmBSgh4tP7999M//mXaa10vp8tV9bcv6Oyh6+X1jtBWClEybqbhcXy9nM5fNxuZB22lbb+dbKWQaP3vn397mB0crXZz3L7OLsdMcw/dvs4vl+SvrkrJ8Wt9DhpE6/Z1Nj6KB9GyPooesNc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VplrefU6BSrl+nJVKiuL5g1YoGuyhvOjaYnH5GSX5udpOmlASI6n9VoWMNadAsd1Q62sty9JauPydBuvuIVl0rT1ryQ6lhGTNSlelsgLRW0lv9gdUqYxPoFUhC6OjFvbs7aFi1XSTAo691fI+VcalUjouP0YBv9rsD6hSUa5/1NE7qxQkWrVV0y8XgzmdcKUV1ZPxtNLzSNLt4qeUlGZ/QJWKcv3fOlrV8m/3VXo/YE4Bp7uInlKC503ysiwvq9DRUr7XqhVdJ3czMUrTLWRmlbwOmo5S9lXHwudlbZPI91pGTwjrt+WhStMNkjU5p4Br314q6c3+ACpVyvVDPyG0eq8lfvUY77VyJf2HK1NKQebKrip5zZVdluvHea9ltO0IUAmBSgiMloBKCFRCYLQEVEKgEgKjJaASApUQGC0BlRCohJBHq16ITAiZJEuaaa9FyO8Do0WICowWISr8H57xi/1dc4/WAAAAAElFTkSuQmCC" alt="" />
解题思路:
1.利用数字辅助表,枚举1-50的自然数列
2.将数字集进行行转列,对5求余作为转列的条件,并按照整除5分组
SQL实现
/*枚举1-50的自然数列*/
WITH x0
AS ( SELECT number
FROM master..spt_values
WHERE type = 'P'
AND number >= 1
AND number <= 50
)
/*行转列*/
SELECT ( number - 1 ) / 5 + 1 AS 行号 ,
MAX(CASE WHEN number % 5 = 1 THEN number
END) AS 第一列 ,
MAX(CASE WHEN number % 5 = 2 THEN number
END) AS 第二列 ,
MAX(CASE WHEN number % 5 = 3 THEN number
END) AS 第三列 ,
MAX(CASE WHEN number % 5 = 4 THEN number
END) AS 第四列 ,
MAX(CASE WHEN number % 5 = 0 THEN number
END) AS 第五列
FROM x0
GROUP BY ( number - 1 ) / 5
很简单。
(本文完)