您可以找到每个位置的位置/
并修剪到MAX(position)
- 根据数据假设第三个/
是最后一个/
。
DECLARE @tbl TABLE ( u VARCHAR(255), t INT, d DATE)
INSERT INTO @tbl (u, t, d) VALUES
('/x', 11, '2013-08-01'),
('/x', 11, '2013-08-01'),
('/pl/', 11, '2013-08-01'),
('/pl/', 11, '2013-08-03'),
('/pl/XXX/', 11, '2013-08-01'),
('/pl/XXX/', 11, '2013-08-04'),
('/pl/XXX/1', 11, '2013-08-01'),
('/pl/XXX/2', 11, '2013-08-01'),
('/pl/YYY/', 11, '2013-08-01'),
('/pl/YYY/1', 11, '2013-08-01'),
('/pl/YYY/2', 11, '2013-08-04'),
('/pl/YYY/3', 11, '2013-08-04')
;WITH split AS (
SELECT u, 1 s, CHARINDEX('/', u) p
FROM @tbl
UNION ALL
SELECT u, p + 1, CHARINDEX('/', u, p + 1)
FROM split
)
SELECT LEFT(t.u, split.i), MAX(t.t), MAX(t.d)
FROM @tbl t
JOIN (
SELECT u, MAX(p) i
FROM split
GROUP BY u
) split ON split.u = t.u
GROUP BY LEFT(t.u, split.i)
通过对 cte 的轻微调整,您可以控制发生
DECLARE @n INT = 3 -- 'nth occurence'
;WITH split AS (
SELECT u, CHARINDEX('/', u) i, 1 r
FROM (
SELECT DISTINCT u
FROM @tbl
) t
WHERE CHARINDEX('/', u) > 0
UNION ALL
SELECT u, CHARINDEX('/', u, i + 1), r + 1
FROM split
WHERE r < @n
AND CHARINDEX('/', u, i + 1) > 0
)
SELECT LEFT(t.u, split.i) u, MAX(t.t) t , MAX(t.d) d
FROM @tbl t
JOIN split ON split.u = t.u
GROUP BY LEFT(t.u, split.i)
sql 小提琴演示