我必须选择具有points>0
但包含在具有points=0
的短语中的最长短语,如果查看演示,则输出中的行将是3和6:< / p>
http://sqlfiddle.com/#!18/e954f/1/0
非常感谢。
答案 0 :(得分:1)
您可以使用内部联接将短语与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;
答案 1 :(得分: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
答案 2 :(得分:0)
您将获得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