我有以下SQL查询:
SELECT DISTINCT ProductNumber,PageNumber FROM table
我正在尝试修改查询,以便格式化PageNumber。你看,PageNumber是以下任何一种格式,其中'x'是一个数字:
我想格式化PageNumber,使其格式为: xxx 。为此,我从以上格式中解析了以下粗体数字:
我想在不编写任何函数的情况下完成所有操作,但我不知道这是否可行。但我无法“检测”所有不同的格式,但是:
这是我到目前为止所做的:
SELECT ProductNumber,
CASE WHEN CHARINDEX(',', PageNumber) > 0
THEN SUBSTRING(PageNumber, 0, CHARINDEX('-', PageNumber))
WHEN CHARINDEX('-', PageNumber) > 0
THEN SUBSTRING(PageNumber, 0, CHARINDEX('-', PageNumber))
ELSE PageNumber
END AS PageNumber
FROM table
WHERE PageNumber IS NOT NULL
AND PageNumber <> ''
有人可以给我一些帮助吗?谢谢!
答案 0 :(得分:3)
使用模式匹配而不是CHARINDEX
CASE还强制进行评估,这有助于第3个案例与前2个案例重叠。
未经测试,如
CASE
WHEN PageNumber LIKE '[0-9][0-9][0-9]%' THEN LEFT(PageNumber, 3)
WHEN PageNumber LIKE '[0-9][0-9]-[0-9][0-9], [0-9][0-9][0-9]') THEN RIGHT(PageNumber , 3)
WHEN PageNumber LIKE '[0-9][0-9]%') THEN LEFT(PageNumber, 2)
END
答案 1 :(得分:2)
试试这个:
DECLARE @YourTable table (ProductNumber int, PageNumber varchar(20))
INSERT @YourTable VALUES (1,'123, 456')
INSERT @YourTable VALUES (2,'123')
INSERT @YourTable VALUES (3,'123-456')
INSERT @YourTable VALUES (4,'12, 345-678')
INSERT @YourTable VALUES (5,'12-34, 567')
INSERT @YourTable VALUES (6,'12-34, 567-789')
;WITH AllNumbers AS ---builds a Numbers table 1-100
( SELECT 1 AS Number
UNION ALL
SELECT Number+1
FROM AllNumbers
WHERE Number<101
)
, RowChars AS --one row for each non-numeric single character value per @YourTable row
( SELECT DISTINCT
ProductNumber,Number, SUBSTRING(PageNumber,Number,1) AS CharacterOF
FROM @YourTable
INNER JOIN AllNumbers ON 1=1
WHERE SUBSTRING(PageNumber,Number,1) IS NOT NULL AND SUBSTRING(PageNumber,Number,1) NOT LIKE '[0-9]' AND SUBSTRING(PageNumber,Number,1)!=''
)
,FirstSplit AS --get first non-numeric single character value per @YourTable row
( SELECT
ProductNumber,MIN(Number) AS SplitOf
FROM RowChars
GROUP BY ProductNumber
)
SELECT
t.ProductNumber, LEFT(t.PageNumber,COALESCE(s.SplitOf-1,LEN(t.PageNumber))) AS NewPage,t.PageNumber AS OldPage
FROM @YourTable t
LEFT OUTER JOIN FirstSplit s ON t.ProductNumber=s.ProductNumber
输出:
ProductNumber NewPage OldPage
------------- -------------------- --------------------
1 123 123, 456
2 123 123
3 123 123-456
4 12 12, 345-678
5 12 12-34, 567
6 12 12-34, 567-789
(6 row(s) affected)