2015-07-07 2 views
1

У меня есть таблица ответов на опрос, которая варьируется от следующих вариантов. Полностью согласен = 5, согласен = 4, нейтральный = 3, согласен = 2, Полностью не согласен = 1Вычисление процентов Благоприятный

таблица выглядит как это:

ID: Q1 Q2 Q3 Q4 Qn 
1 5 4 5 3 2 
2 4 5 2 1 4 
3 4 4 3 2 3 
4 5 4 3 4 3 

Я использую следующий фрагмент кода MySQL чтобы взять одну колонку и создать 3 дополнительных столбца для процентов благоприятных, нейтральных и неблагоприятных.

Select 
(case when Q1 = 5 or Q1 = 4 then 1 else null end) as Q1Fav, 
(case when Q1 = 3 then 1 else null end) as Q1Neu, 
(case when Q1 = 2 or Q1 = 1 then 1 else null end) as Q1UnFav 
From survey_data 

Это дает мне благоприятные отклики на Q1 в одной колонке, нейтральные ответы в другой колонке и т.д.

Есть ли способ, чтобы расширить это, чтобы сделать MySQL продолжать генерировать эти столбцы, пока не дошло до Qn ? (где Qn - последний из вопросов опроса и последний столбец в моем списке).

Благодарим за помощь!

ответ

0

- Это должно быть все, что вам нужно.

- У вас может быть 9 миллионов обследований.

- У одного может быть 200 вопросов, а у другого может быть 4. Неважно.

create table users 
(
    userId int auto_increment primary key, 
    fName varchar(100) not null, -- Stan 
    lName varchar(100) not null  -- Smith 
)ENGINE=MyIsam; 

create table surveys 
(
    surveyId int auto_increment primary key, 
    sTitle varchar(255) not null, 
    dtCreated date not null -- date created in system 
)ENGINE=MyIsam; 

-- create table questions 
-- ( -- to keep things simple to start, assume questions are not in mysql 
    -- that can be for version Beta 0.02 
--); 

create table UserTakesSurvey 
( -- A user takes a survey (this is going to be useful) 
    -- 1 row for each combo kinda obvious 
    userId int not null, 
    surveyId int not null, 
    dtTaken date not null, 

    -- Foreign Key constraints go here: 
    -- to Users Table: 
    FOREIGN KEY (userId) REFERENCES users(userId), 
    -- to Surveys Table: 
    FOREIGN KEY (surveyId) REFERENCES surveys(surveyId), 
    -- so no row can exist here with a wrong (non-existing) userId or surveyId 

    -- addition indexes here: 
    primary key (userid,surveyid), 
    key (surveyid,userid) 
)ENGINE=MyIsam; 

create table answers 
( id int auto_increment primary key, 
    userId int not null, 
    surveyId int not null, -- survey id 
    qNum int not null, -- question number 
    answer int not null, -- 5 to 1 

    -- Foreign Key constraints go here: 
    -- to Users Table: 
    FOREIGN KEY (userId) REFERENCES users(userId), 
    -- to Surveys Table: 
    FOREIGN KEY (surveyId) REFERENCES surveys(surveyId), 
    -- so no row can exist here with a wrong (non-existing) userId or surveyId 

    -- Additional indexes go here: 
    -- create a composite (combo) key incorporating two columns 
    KEY (userId,surveyId), 
    KEY (surveyId,userId) 
)ENGINE=MyIsam; 

insert users (fName,lName) values ('Stan','Smith'),('Sally','Higgins'); 

-- first survey will have 7 questions hypothetically, 2nd 101 questions 
insert surveys (sTitle,dtCreated) values ('Feelings about Milk','2013-01-17'); 
insert surveys (sTitle,dtCreated) values ('Thoughts on Global Warming',curdate()); 

.

-- we now have 2 users, 2 surveys 
-- Stan is id=1, Sally is id=2. Ditto for survey numbers starting at 1 and up. 
-- in web loop, say PHP or whatever, you are collecting question answers 
-- loop thru upon Final Submit and do your inserts into table 'answers' (one row each) 

-- Assuming for now surveys themselves for simplicity exist on paper/webpage without questions embedded in database (which is not a problem). 

-- But trying to simplify the example. Also note that answers.answer is not null but it can be null (no user answer). 

-- One table contains all answers without the need to monkey around with creating columns as you were. 
-- That monkeying around would be an answers table for each survey, bad idea. 

-- This will perform very fast, and data is easily accessible as if in the format you desire. 
-- It may not be readily obvious how, but then again what are followup questions for :> 
-- So that question is something like "How do I get at my data" ! 
+0

Дрю, большое вам спасибо за помощь. У меня возникли проблемы с ответом. Я начинающий пользователь MySQL, и я был бы признателен за вашу помощь, пройдя через это немного. – Alexander

+0

Без проблем позвольте мне добавить еще займет 15 минут – Drew

+0

Спасибо. Если это помогает, и в случае, если это неясно, каждая запись в таблице, в которой я работаю, представляет собой ответчика на опрос, а столбцы представляют собой сами опросные вопросы. – Alexander

Смежные вопросы