作者KerKerLaugh (科科笑)
看板Database
標題[SQL ] 將值計算再新增到資料表
時間Wed Jul 2 11:25:45 2014
取likes欄位數字的第一個字元,分組計算1~9各有幾筆
SELECT substring( likes, 1, 1 ) as Leading_Digits, Count( * ) as Actual_Count
FROM movies
GROUP BY substring( likes, 1, 1 )
結果
Leading_Digits Actual_Count
1 30
2 12
3 10
4 13
5 8
6 4
7 8
8 10
9 6
總筆數是101筆
我想在Actual_Count右邊再新增一欄名為Expected_Count
Expected_Count 9行的值為101 * 0.301
101 * 0.176
101 * 0.125
101 * 0.097
101 * 0.079
101 * 0.067
101 * 0.058
101 * 0.051
101 * 0.046 的結果
(變數) (固定值)
請問這要怎麼新增
另有一張test的資料表包含
Leading_Digits Probability
1 0.301
2 0.176
3 0.123
4 0.097
5 0.079
6 0.067
7 0.058
8 0.051
9 0.046
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.123.176.231
※ 文章網址: http://webptt.com/m.aspx?n=bbs/Database/M.1404271550.A.1A6.html
※ 編輯: KerKerLaugh (140.123.176.231), 07/02/2014 11:59:13
1F:推 bohei:先來釐清一下,新增欄位這塊跟上面的關聯只有101這個值嗎? 07/02 12:13
2F:→ KerKerLaugh:101是movies資料表的總筆數 要用任一資料表的總筆數 07/02 12:17
3F:→ KerKerLaugh:乘上那9個固定值的結果 07/02 12:17
4F:→ bohei:GROUP BY後的總和為101,其實也就是movies內的總筆數.. 07/02 12:19
5F:→ bohei:先ALTER欄位,再用UPDATE Expected Count=總筆數*固定值 07/02 12:20
6F:→ bohei:這樣應該就符合你的要求了吧? 07/02 12:20
7F:→ bohei:OH..想到..每列的固定值都不一樣,這有很多解法 07/02 12:21
8F:→ bohei:用另一個TEMP TABLE先記錄PK跟固定值,然後從TEMP這邊撈值過 07/02 12:22
9F:→ bohei:去UPDATE 07/02 12:22
10F:→ bohei:不然就在UPDATE裡面寫CASE每一列的固定值 07/02 12:23
11F:→ bohei:不然就是找出固定值的計算公式,就不必寫死每一列的值了 07/02 12:24
12F:推 cutekid:有沒有 table 記錄 「Leading_Digits」和「固定值」的關係 07/02 13:11
13F:推 cutekid:如果沒有 table 記錄的話,想請問你用的是什麼 database 07/02 13:17
14F:→ KerKerLaugh:我用mysql 07/02 13:46
15F:→ cutekid:leading digits 跟 固定值,有沒有另一個 table 做記錄?? 07/02 13:53
16F:→ KerKerLaugh:我剛剛新增一個紀錄Leading_Digits和固定值的table了 07/02 13:59
※ 編輯: KerKerLaugh (140.123.176.231), 07/02/2014 14:27:43
17F:→ bohei:expected_count=COUNT(*)*Probability即可 07/02 15:15
18F:→ bohei:上面一句推錯了,要推在下面那篇 07/02 15:15