[英]Select by length of characters
我必须选择points>0
但包含在points=0
的短语中的最长短语,如果查看演示,则输出中的行将是数字3和6:
http://sqlfiddle.com/#!18/e954f/1/0
提前谢谢了。
您可以使用内部联接将短语与LIKE
进行比较,以仅获取包含在另一个短语中的短语。 在WHERE
子句中过滤点。 然后从连接的实例中获取由短语划分的rank()
,并按长度递减的顺序排序。 在外部SELECT
仅获得等级为1的那些。
SELECT x.id,
x.phrase,
x.points
FROM (SELECT w1.id,
w1.phrase,
w1.points,
rank() OVER (PARTITION BY w2.phrase
ORDER BY len(w1.phrase) DESC) r
FROM words w1
INNER JOIN words w2
ON w2.phrase LIKE concat(w1.phrase, '%')
WHERE w2.points = 0
AND w1.points > 0) x
WHERE x.r = 1;
编辑:
包括其他短语:
SELECT x.id,
x.phrase,
x.other_phrase,
x.points
FROM (SELECT w1.id,
w1.phrase,
w2.phrase other_phrase,
w1.points,
rank() OVER (PARTITION BY w2.phrase
ORDER BY len(w1.phrase) DESC) r
FROM words w1
INNER JOIN words w2
ON w2.phrase LIKE concat(w1.phrase, '%')
WHERE w2.points = 0
AND w1.points > 0) x
WHERE x.r = 1;
您可以使用CTE查找所有带有正点的短语,这些短语是具有0点的短语的子字符串。 然后,您可以找到与每个0点短语相关联的子字符串的最大长度,并将其JOIN
回CTE以获取与该条件匹配的短语:
WITH cte AS (
SELECT w1.*, w2.id AS w2_id
FROM words w1
JOIN (SELECT *
FROM words
WHERE points = 0) w2 ON w1.phrase = LEFT(w2.phrase, LEN(w1.phrase))
WHERE w1.points > 0
)
SELECT cte.id, cte.phrase, points
FROM cte
JOIN (SELECT w2_id, MAX(LEN(phrase)) AS max_len
FROM cte
GROUP BY w2_id) cte_max ON cte_max.w2_id = cte.w2_id AND cte_max.max_len = LEN(cte.phrase)
输出:
id phrase points
3 tool box online 1
6 stone road 1
您将从短语的最大长度到最小长度,其中points>0
SELECT *, LEN(phrase) AS Lenght FROM words where points>0 ORDER BY LEN(phrase) DESC
如果你想要最长的短语
SELECT TOP 1 *, LEN(phrase) AS Lenght FROM words where points>0 ORDER BY LEN(phrase) DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.