Sql-Server
連接表並根據段計算它們 SQL
我有 2 張桌子,我正在嘗試加入併計算有多少人回答了每個問題。我正在嘗試找到一種只有兩列的更好方法。第一個是回答“只是我,我的配偶/伴侶”的人,另一列是回答兒童 0-5 歲、6-12 歲、13-17 歲的人。我正在嘗試找出一種更好的方法來擁有一張看起來像這樣的桌子
Question Answer Children Justme/partner do you buy milk weekly 400 20 do you consume cheese daily 15 300 how many time you drive daily 400 220
這是 2 個表格 這是提供的稱為“家庭”的表格:
User JustMe Children 0-5 Children 6-12 Myspouse/partner 5 N N N N 5 N N N N 4 N N N N 4 N N N N 12 N N N N 12 Just Me N N Myspousepartner 46 Just Me N Children 6-12 years Mypousepartner 46 Just Me N Children 6-12 years Mypousepartner
調查表
User questionid answerid question answer 4 2 5 how often you buy gas weekly 46 3 4 how often you buy milk monthly 75 3 4 how often you buy milk weekly 13 4 2 how often you use coupon monthly
我用
SELECT id,question, Children_0_5_years, Children_6_12_years, Children_13_17_years, count(*) AS NEW_COUNT FROM table1 inner join table2 on table1.user=table2.user group by...
不幸的是,這個查詢返回了我不需要的東西。
`SELECT Question, SUM( CASE –Case for each column WHEN h.“Children 0-5” = ‘Children 0-5’ THEN 1 Else 0 END) as “Children 0-5”, SUM( CASE
WHEN h.“Children 6-12” = ‘Children 0-5’ THEN 1 Else 0 END as “Children 0-5”* from household h INNER JOIN survey s ON h.user = s.user GROUP BY s.question, answer`
好的,從我的大腦中做這件事而不是測試,但這是我的想法。使用 case 語句將您的字元串數據轉換為可求和的數字。然後按問題分組以匯總答案。
如果我是您(並且您可以更改數據),我將擺脫冗長的字元串欄位,並製作諸如年齡組 Y、N 甚至更好的 1、0 之類的東西。