sum函数与join

时间:2013-10-08 05:44:13

标签: sql sql-server sql-server-2008

我有两个表格关键字和帖子

关键字表格如

       keyword    weight
         1         0.3
         2         0.5 
         3         0.4 

例如

和发表表格

         post
       i am beautiful
       1, 2, 3
       1 + 3 = 4

如果我想从帖子表中加权总和

意味着

我希望得到结果

     post     total 
    1, 2, 3     1.2
    1 + 3 = 4   0.7
像这样

我应该使用join子句吗?

 create procedure RankingPost8
 (@concept_name nvarchar(50))
 AS
 declare @k1 nvarchar(200) 
 select @k1 = keyword from keyword where concept_id = 
 (select Concept_ID from concept where @concept_name = Concept_name) 
 Select @K1 = coalesce(@k1 +' ','') + keyword  from keyword
 begin
 select id as Post_ID, post as Txt from Post 
  where freetext (post, @k1) 

 end 

2 个答案:

答案 0 :(得分:0)

一种可能的解决方案是使用光标。

尝试这样的事情:

UPDATE POST 
SET    TOTAL = 0 

DECLARE @keyword INT, 
        @weight  NUMERIC(4, 2) 
DECLARE CURS CURSOR FAST_FORWARD READ_ONLY FOR 
  SELECT * 
  FROM   KEYWORD 

OPEN CURS 

FETCH NEXT FROM CURS INTO @keyword, @weight 

WHILE @@FETCH_STATUS = 0 
  BEGIN 
      UPDATE POST 
      SET    TOTAL = TOTAL + @weight 
      WHERE  CHARINDEX(CAST(@keyword AS VARCHAR(4)), POST) > 0 

      FETCH NEXT FROM CURS INTO @keyword, @weight 
  END 

CLOSE CURS 

DEALLOCATE CURS 

SELECT POST, 
       TOTAL 
FROM   POST 
WHERE  TOTAL > 0 

可以在SQL Fiddle找到一个工作示例。

在我的示例中,我在Post表中添加了一个包含最终值的列。如果您想要在不同的表格中或仅在输出中而不更改原始表格,请告诉我。

答案 1 :(得分:0)

你为什么不尝试这样的事?

SELECT post, sum(weight)
FROM Post
INNER JOIN Keyword ON post LIKE '%'+ Convert(varchar,keyword) + '%'
GROUP BY post

SQL Fiddle上试用。

我留给你为你的参数添加where条件:)

希望你喜欢它。