;WITH MATCH_START AS
(
SELECT LI.POS, LI.LINEITEMID, PRODUCT.PRODUCTRANGE, LI.DESCRIPTION
FROM (SELECT ROW_NUMBER() OVER (ORDER BY LINEITEMID) POS, LINEITEMID, DESCRIPTION FROM LINEITEM) LI
JOIN PRODUCT ON LI.DESCRIPTION LIKE PRODUCT.PRODUCTRANGE+'%'
),
MATCH_CONTAINS AS
(
SELECT LI.POS, LI.LINEITEMID, PRODUCT.PRODUCTRANGE, LI.DESCRIPTION
FROM (SELECT ROW_NUMBER() OVER (ORDER BY LINEITEMID) POS, LINEITEMID, DESCRIPTION FROM LINEITEM) LI
JOIN PRODUCT ON LI.DESCRIPTION LIKE '%'+PRODUCT.PRODUCTRANGE+'%'
),
MIN_START_POS AS (
SELECT MIN(POS) AS MIN_POS, PRODUCTRANGE FROM MATCH_START
GROUP BY PRODUCTRANGE
),
MIN_CONTAIN_POS AS (
SELECT MIN(POS) AS MIN_POS, PRODUCTRANGE FROM MATCH_CONTAINS
GROUP BY PRODUCTRANGE
)
SELECT MS.PRODUCTRANGE,MS.DESCRIPTION, MS.LINEITEMID FROM MATCH_START MS
JOIN MIN_START_POS MSP ON MS.POS = MSP.MIN_POS AND MSP.PRODUCTRANGE = MS.PRODUCTRANGE
UNION
SELECT MC.PRODUCTRANGE, MC.DESCRIPTION, MC.LINEITEMID FROM MATCH_CONTAINS MC
JOIN MIN_CONTAIN_POS MCP ON MC.POS = MCP.MIN_POS AND MCP.PRODUCTRANGE = MC.PRODUCTRANGE
AND MC.PRODUCTRANGE NOT IN (SELECT PRODUCTRANGE FROM MATCH_START)
--首先匹配以单词开头的productRange,然后匹配containint。
例如使用此数据:SELECT * FROM LINEITEM
LineItemId Description
----------- --------------------------------------
1 Sony Headphones for a Sony DHJ232
2 Sony DHJ232 in blue
3 SANYO KI8767 with carry case
4 SANYO KI8767 with carry case 2
5 Sony Headphones for a Sony DHJ232 B
从产品中选择 *
ProductRange
----------------------
SANYO KI8767
Sony DHJ232
Sony Headphones
结果是
PRODUCTRANGE DESCRIPTION LINEITEMID
--------------- ------------------------------------- -----------
SANYO KI8767 SANYO KI8767 with carry case 3
Sony DHJ232 Sony DHJ232 in blue 2
Sony Headphones Sony Headphones for a Sony DHJ232 1