2014-08-27 73 views
0

我有两个表格,一个字词频率表格和一个字词权重表格。 我需要编写一个t-sql脚本或脚本来根据单词权重表中给出的单词和权重来计算单词频率表的加权分数。在两个表格之间乘以公共值

例如: 字频率表

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

字权重表

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

从这两表中的加权分数将工作证明是(5×)+(7x3)= 31 然后我需要打印结果,如果超过30“警报!评分超过30”或者低于30则“正常,评分低于30”。

我很高兴创建打印脚本,一旦计算得分,但我不太确定如何到达那里。

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

我可能会离开,但我正在计算两个表之间的连接,基于哪里w.word = f.word ??

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

回答

4

应该

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 
0
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 
相关问题