首页 文章

将两个表之间的公共值相乘

提问于
浏览
0

我有两个表,一个单词频率表和一个单词权重表 . 我需要编写一个t-sql脚本或脚本来根据单词权重表中给出的单词和权重来计算单词频率表的加权分数 .

例如:Word频率表

Word   Frequency
,,,,,,,,,,,,,,,,
Fat        3
Ugly       2
dumb       2
stupid     3

单词重量表

Word    Weight
,,,,,,,,,,,,,,
Ugly      5
stupid    7

这两个表格的加权分数可能是(5x2)(7x3)= 31我需要打印结果,如果超过30“警报!得分超过30”或者如果低于30那么“正常,得分低于30” .

一旦计算得分,我就可以创建打印脚本,但我不太清楚如何到达那里 .

脚本需要能够允许更改表,所以我猜它只需要在它们之间寻找公共值然后加入列 .

我可能会离开但我正在根据w.word = f.word在哪里找到两个表之间的连接?

我整个下午一直在寻找解决方案,真的没有得到任何结果 . 任何帮助,将不胜感激!

4 回答

  • 0

    它应该是

    select sum (w.Weight * f.Frequency) from WeightTable w
    join FreqTable f  on f.Word = w.Word
    
  • 0

    如果一个表包含所有单词,那么您可以按建议使用左连接,但如果没有,那么完整的外连接将起作用 .

    SELECT 
        COALESCE(t1.word, t2.word) AS word
        , COALESCE(t1.frequency, 1) AS frequency
        , COALESCE(t2.weight, 1) AS weight
        , COALESCE(t1.frequency, 1) * COALESCE(t2.weight, 1) AS score
        , CASE WHEN COALESCE(t1.frequency, 1) * COALESCE(t2.frequency, 1) > 30 
                    THEN 'Alert! Score over 30'
                    ELSE 'Normal, score under 30' AS message END
    FROM word_frequency t1
    FULL OUTER JOIN word_weight t2
    ON t1.word = t2.word
    
  • 4
    select  case when SUM( cast(fr as numeric )* cast (weight as numeric))  >30 then 'ABove 30'
    else 'below 30' end from table1 inner join 
    table2 on table1.word=table2.word
    
  • 0

    只是为了证明@wraith的答案,这里是代码:

    declare @WordFreq table (Word varchar(max), Frequency int );
    declare @WordWeight table (Word varchar(max), Weight int );
    
    insert into @WordFreq( Word, Frequency ) values
      ( 'Fat', 3)
    , ( 'Ugly', 2)
    , ( 'dumb', 2)
    , ( 'stupid', 3)
    
    insert into @WordWeight( Word, Weight ) values
      ( 'Ugly', 5)
    , ( 'stupid', 7)
    
    select sum (w.Weight * f.Frequency)
      from @WordFreq f
    join @WordWeight w on f.Word = w.Word
    -----------------------
    OUTPUT: 31
    

相关问题