多条记录并为变成一条记录(有点怪)
-------------------
联赛A null
主队a1 比分00
客队a2 null
联赛B null
主队b1 比分01
客队b2 null
.
.
.
数据库中要实现如下格 式:
----------------
联赛A 主队a1 客队a2 比分00
.
.
.
[解决办法]
CREATE TABLE tb
(
col VARCHAR(20),
col1 VARCHAR(20)
)
INSERT INTO tb
SELECT '联赛A',NULL UNION ALL
SELECT '主队A1','比分00' UNION ALL
SELECT '客队A2',NULL UNION ALL
SELECT '联赛B',NULL UNION ALL
SELECT '主队B1','比分01' UNION ALL
SELECT '客队B2',NULL
SELECT COL1 = A.col, COL2 = B.col, COL3 = C.COL, COL4 = ISNULL(A.col1,ISNULL(C.col1,B.col1))
FROM
(
SELECT ID = CASE WHEN LEN(RTRIM(STUFF(col,1,PATINDEX('%[A-Za-z]%',LTRIM(col)),''))) = 0
THEN 0
ELSE STUFF(col,1,PATINDEX('%[A-Za-z]%',LTRIM(col)),'')
END,
M = SUBSTRING(col,PATINDEX('%[A-Za-z]%',LTRIM(col)),1),
*
FROM tb
) A
INNER JOIN
(
SELECT ID = CASE WHEN LEN(RTRIM(STUFF(col,1,PATINDEX('%[A-Za-z]%',LTRIM(col)),''))) = 0
THEN 0
ELSE STUFF(col,1,PATINDEX('%[A-Za-z]%',LTRIM(col)),'')
END,
M = SUBSTRING(col,PATINDEX('%[A-Za-z]%',LTRIM(col)),1),
*
FROM tb
) B ON A.M = B.M
INNER JOIN
(
SELECT ID = CASE WHEN LEN(RTRIM(STUFF(col,1,PATINDEX('%[A-Za-z]%',LTRIM(col)),''))) = 0
THEN 0
ELSE STUFF(col,1,PATINDEX('%[A-Za-z]%',LTRIM(col)),'')
END,
M = SUBSTRING(col,PATINDEX('%[A-Za-z]%',LTRIM(col)),1),
*
FROM tb
) C ON A.M = C.M
WHERE A.id = 0 AND CHARINDEX('主',B.col) >0 AND CHARINDEX('客',C.col)>0
DROP TABLE tb
(所影响的行数为 6 行)
COL1 COL2 COL3 COL4
-------------------- -------------------- -------------------- --------------------
联赛A 主队A1 客队A2 比分00
联赛B 主队B1 客队B2 比分01
(所影响的行数为 2 行)