2014-08-27 57 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 
相關問題