[英]Using a column from a subquery in another subquery & selecting multiple column in subquery
[英]Column as a subquery
需要有一個第3列,它將對每個第1列(單詞)的所有點求和,但是它將對每行的'%word%'之類的所有單詞的點進行求和,例如'chef'這個單詞將具有'廚師'和'廚師廚師'等點
SELECT word, SUM(points) as points
FROM table
group by word
你可以測試一下。 然而,加入LIKE並不是很有效。
;WITH Words AS(
SELECT word ,sum(points) as points,
FROM table group by word
)
SELECT
W.word,
W.points,
LikeWordPoints = W.points + ISNULL(SUM(LikeWord.points),0)
FROM
Words W
LEFT OUTER JOIN Words LikeWord ON LikeWord.word LIKE '%'+W.word+'%' AND LikeWord.word <> W.word
GROUP BY
W.word,
W.points
如果我理解正確,我可能會使用correlated subquery
:
select distinct w.word,
(select sum(points) from words w2 where w2.word like '%' + w.word + '%') as points
from words w
選擇中的相關子查詢可能會降低性能。 我建議使用加入或交叉申請
select distinct w.word, C.SumOfPoints as sumofpoints
from words w
CROSS APPLY (SELECT SUM(points) AS SumOfPoints from words w2 WHERE w2.word like '%' +
w.word + '%') C
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.