英文:
Split string in row into separate string (into a column)
问题
SQL 查询:
输入:
| 公司 |
| --------|
| 苹果 |
| 谷歌 |
需要的输出:
| 一 | 二 |
|----------|
| A | G |
| P | O |
| P | O |
| L | G |
| E | L |
| | E |
尝试使用 string_split 函数。新手 SQL。无法获得所需的输出。请帮助
英文:
SQL Query:
Input:
| Company |
| --------|
| APPLE |
| GOOGLE |
Needed Output:
|One | Two |
|----------|
| A | G |
| P | O |
| P | O |
| L | G |
| E | L |
| | E |
Tried using string_split function.
New to SQL. Can't get the desired output. Please help
答案1
得分: 1
I'll provide the translation of the code portion you provided:
我真的不确定你在这里想要实现什么,但为了生成你要求的结果集:
DECLARE @TABLE TABLE (Company NVARCHAR(50));
INSERT INTO @TABLE (Company) VALUES
('苹果'),('谷歌'),('微软'),('Meta');
;WITH Numbers AS (
SELECT 1 AS Number, (SELECT MAX(LEN(Company)) FROM @TABLE) AS MaxNumber
UNION ALL
SELECT Number+1, MaxNumber
FROM Numbers
WHERE Number < MaxNumber
)
SELECT MAX([1]) AS one, MAX([2]) AS two, MAX([3]) AS three, MAX([4]) AS four
FROM (
SELECT *, SUBSTRING(Company,Number,1) AS c
FROM (SELECT Company, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS Rn FROM @TABLE) a
CROSS APPLY Numbers
) a
PIVOT (
MAX(c) FOR Rn IN ([1],[2],[3],[4])
) p
GROUP BY Number
请注意,代码部分已被翻译为中文。
英文:
I'm really not sure what you're looking to achieve here, but to produce the result set you asked for:
DECLARE @TABLE TABLE (Company NVARCHAR(50));
INSERT INTO @TABLE (Company) VALUES
('Apple'),('Google'),('Microsoft'),('Meta');
;WITH Numbers AS (
SELECT 1 AS Number, (SELECT MAX(LEN(Company)) FROM @TABLE) AS MaxNumber
UNION ALL
SELECT Number+1, MaxNumber
FROM Numbers
WHERE Number < MaxNumber
)
SELECT MAX([1]) AS one, MAX([2]) AS two, MAX([3]) AS three, MAX([4]) AS four
FROM (
SELECT *, SUBSTRING(Company,Number,1) AS c
FROM (SELECT Company, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS Rn FROM @TABLE) a
CROSS APPLY Numbers
) a
PIVOT (
MAX(c) FOR Rn IN ([1],[2],[3],[4])
) p
GROUP BY Number
This is pretty gnarly, and would need to be manually adjusted to produce more results (unless you go down the dynamic SQL pivot road).
Essentially what we're doing here is building a CTE to hold the numbers from 1 to the length of the longest string and then applying it to the data. Using that number we can produce a substring of 1 from that position. Then to put them into columns (from rows) we pivot on the ROW_NUMBER
(in no particular order) and produce the MAX string value for each rows position. Finally, to compress the result down into a single set of rows we take the MAX value for each position grouped by that row number.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论