MySQL Pivot Prepare Statement AS Integer error - mysql

Probably a very basic error but here is my problem.
There are users who are giving likes to certain pages of a given document and my aim is to return a breakdown of pages liked per user
Here are (a simplified view of) the two following tables:
User table
id name
---------
1 Jim
2 John
Vote table
userid pageno voteup
1 1 1
1 2 1
2 1 1
2 2 1
2 3 1
My desired output would be the following:
id name Page 1 Page 2 Page 3
1 Jim 1 1 0
2 John 1 1 1
I've made my prepared statement as followed. My aim is to display 'Page 1', 'Page 2' and so on for the column names instead of the 'test' below but as my pageno field is an int i fail in formatting the column name. I have tried various things but with no luck.
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(v.pageno = ',
pageno,
', v.voteup, 0)) AS ',
'test'
)
) INTO #sql
FROM vote;
SET #sql = CONCAT('SELECT u.id, u.name, ', #sql, '
FROM user u
LEFT JOIN vote AS v
ON u.id = v.id
GROUP BY u.id');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I'm sure this is something very basic I am missing. Could you help?
Thanks in advance
Link to SQLFiddle

This will do the trick although is not dynamic, if you need a dynamic solution.....
select
n.id,
n.name,
CASE WHEN v.pageno=1 THEN sum(v.voteup) ELSE NULL END as "Page 1"
CASE WHEN v.pageno=2 THEN sum(v.voteup) ELSE NULL END as "Page 2"
from votetable as v
join usertable as n on n.id = v.userid

Related

Mysql select dynamic row values as column name from a table and value from another table

I have arranged a survey where a project has some questions. Users have to collect the given project answer from public. Survey tables like
user tables
user_id user_name
1 User 1
2 User 2
Project table
project_id project_name
1 project 1
2 project 2
Question table
ques_id project_id ques_name
1 1 Question 1
2 1 Question 2
3 1 Question 3
4 1 Question 4
Answer table
ans_id public_id user_id ques_id ques_ans
1 1 1 1 Answer 1
2 1 1 2 Answer 2
3 1 1 3 Answer 3
4 1 1 4 Answer 4
Now i want to generate a reports where question table values as column name matched by given project_id and question answers as value from answer table matched by ques_id
And, her is my expected output:
User_Name public_id Question 1 Question 2 Question 3 ...
User 1 1 Answer 1 Answer 2 Answer 3 ...
Someone suggested to use pivot but i found "MySQL doesn't have native support for pivoting operations" can anyone help me out?
You can use another output format of the query. For example:
SELECT user_name, answer.project_id, ques_name, ques_ans
FROM
`answer`
INNER JOIN `user` USING (user_id)
INNER JOIN `question` USING (ques_id);
To restrict rows by specific project add WHERE clause:
WHERE project_id = #ProjectID
Then transform the result to the desired view using PHP.
If it is critical to solve the question using MySQL then create new colums manually using aliaces. To aggregate rows by user and project use GROUP BY clause. To show the possible non-empty values use MAX() function. In your case:
SELECT
user_name, project_id,
MAX(IF(ques_name = 'Question 1', ques_ans, NULL)) AS `Question 1`,
MAX(IF(ques_name = 'Question 2', ques_ans, NULL)) AS `Question 2`,
MAX(IF(ques_name = 'Question 3', ques_ans, NULL)) AS `Question 3`,
MAX(IF(ques_name = 'Question 4', ques_ans, NULL)) AS `Question 4`
FROM
(SELECT
ans_id, user_id, user_name, answer.project_id, ques_name, ques_ans
FROM
answer
INNER JOIN `user` USING (user_id)
INNER JOIN question USING (ques_id)
) AS tmp
GROUP BY
user_id, project_id;
Finally the code is working
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(a.ques_id = ',
ques_id,
', a.ques_ans, NULL)) AS `',
ques_name,'`'
)
) INTO #sql
FROM survey_answer inner join survey_question on survey_answer.ques_id=survey_question.id;
set #sql = CONCAT('select u.user_name ,q.category_id,a.p_code, ' ,#sql,' FROM `survey_answer` as a
LEFT JOIN `users` as u ON a.user_id = u.user_id
LEFT JOIN `survey_question` as q ON a.ques_id= q.id');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
your query should be :
SELECT an.user_name,an.public_id,qs.quest_name,an.quest_answer
FROM answer_table an,question_table qs,user_table usr
WHERE an.quest_id = qs.quest_id
AND an.user_id=usr.user_id
For the table rotation : here a similar question about rotating tables
mysql pivot table date (vertical to horizontal data)

row value is column name of 2nd table, need result from 2nd table

I need to create a view from 2 tables
Table 1
app_id cat_id approver level proj_id
1 1 pm_id 1 731
1 2 dm_id 2 843
1 3 dm_id 1 859
2 4 bo_id 1 859
table 2
proj_id pm_id dm_id bo_id
731 100102 100034 100121
843 123121 145721 104321
859 112312 132434 132435
My approver id is in table 2 and the table 1 denotes who is the approver for the project based on the level. I want to create a view for the list of approval pending with the pm, dm and bo.
e.g. result table
app_id cat_id approver
1 1 100102
1 2 145721
1 3 132434
2 4 132435
Use left join to join two tables together, then use case when to get approver.
select
table1.app_id,
table1.cat_id,
case when table1.approver = 'pm_id' then table2.pm_id
when table1.approver = 'dm_id' then table2.dm_id
when table1.approver = 'bo_id' then table2.bo_id
end as approver
from table1
left join table2 on table1.proj_id = table2.proj_id
See demo in rextester.
Edit:
If you have dynamic approver, try this:
SET #sql = NULL;
SELECT
CONCAT('CASE', GROUP_CONCAT(DISTINCT
CONCAT(' WHEN table1.approver = ''',
approver,
''' THEN table2.', approver) SEPARATOR ' '), ' END AS approver'
) INTO #sql
FROM table1;
SET #sql = CONCAT('SELECT table1.app_id, table1.cat_id, ', #sql, ' FROM table1 LEFT JOIN table2 ON table1.proj_id = table2.proj_id');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Also have a demo in Rextester.
Create VIEW:
create view view1
as
select
table1.app_id,
table1.cat_id,
case when table1.approver = 'pm_id' then table2.pm_id
when table1.approver = 'dm_id' then table2.dm_id
when table1.approver = 'bo_id' then table2.bo_id
end as approver
from table1
left join table2 on table1.proj_id = table2.proj_id

Geting the columns as rows from a single table in mysql [duplicate]

This question already has answers here:
How can I return pivot table output in MySQL?
(10 answers)
Closed 8 years ago.
I have one table like below here I need to get subject row as column and attendance as rows
sid name subject attendance
1 jhon sub1 1
2 toni sub1 0
3 danial sub1 1
4 jafer sub1 1
5 jhon sub2 1
6 toni sub2 1
7 danial sub2 1
8 jafer sub2 0
According to my requirements I need to get the output like the following table :
name sub1 sub2
jhon 1 1
toni 0 1
danial 1 1
jafer 1 0
I am new at writing queries in mysql.
Thanks in advance for your help!
You can use the following technique to achieve this, note that it only works when you know the total variations in your case its just sub1 and sub2 , if there are more you need to add them in the query or generate a complete dynamic query
select
name,
max(case when subject='sub1' then attendance end ) as 'sub1',
max(case when subject='sub2' then attendance end ) as 'sub2'
from test
group by name
DEMO
To make it dynamic its a bit complicated, google it about mysql dynamic pivoting and you will get some tutorial to understand how it works.
For your case you can have like below -
set #d_sql = null;
select
group_concat(distinct
concat(
'max(case when subject = ''',
subject,
''' then attendance else null end) as ',
concat('`',subject, '`')
)
) into #d_sql
from test;
set #d_sql = concat('SELECT name,', #d_sql, ' from test group by name');
PREPARE stmt from #d_sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
DEMO

MySQL - Select Query with junction table to one row

i have the following tables:
**entries**
entry_id | date | engineer | project
**entries_allowanes_map**
entry_id | allowance_id
**allowances**
allowance_id | allowance_name
I want to create a SELECT query that will give the following result:
entry_id | date | engineer | project | allowance_name1 | allowance_name2 | allowance_name_n...
The queries I have tried return a row for each allowance an entry has registered with. I want just one row with all allowances attached to it.
Thanks in advance
I would propose doing this with group_concat(). It doesn't put the values in separate columns, but it does put everything for a given entry on one row:
select e.entry_id, e.date, e.engineer, e.project,
group_concat(a.allowance_name) as allowances
from entries e join
entries_allowances_map f
on e.entry_id = eam.entry_id
allowances a
on eam.allowance_id = a.allowance_id
group by e.entry_id;
Here is the query that I got:
It outputs your expected results in different columns:
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'(SELECT max(CASE WHEN AL.ALLOWANCE_ID = ''',
ALLOWANCE_ID,
''' THEN 1 END) AS `',
ALLOWANCE_ID, '` FROM entries_allowanes_map AL WHERE E.ENTRY_ID = AL.ENTRY_ID ) AS `',
ALLOWANCE_NAME, '`'
)
) INTO #sql
FROM allowances;
SET #sql
= CONCAT('SELECT E.ENTRY_ID, E.DATE, E.ENGINEER, E.PROJECT, ', #sql, '
FROM entries as e');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Here is the SqlFiddle
Try
SELECT * FROM entries as e
INNER JOIN entries_allowanes_map as a ON e.entry_id=e.entry_id
INNER JOIN allownces as al ON al.allownce_id=a.allowance_id

Pivot Table Using MySQL

I have two tables Triples and Tags
Triples Table has the following Columns
id PostID TagID Value
1 1 1 Murder
2 1 2 New Brunswick
3 2 1 Theft
4 2 3 Gun
Tags Table has the following Columns
id TagName
1 Incident
2 Location
3 Weapon
I am trying to write sql to create a Pivot Table with Dynamic Headers
Output should be like this
PostID Incident Location Weapon
1 Murder New Brunswick
2 Theft Gun
Any help in writing the SQL would be appreciated. I have seen examples online but could not figure out this one
In order to pivot the data in MySQL, you will need to use both an aggregate function and a CASE expression.
If you have a known number of columns, then you can hard-code the query:
select p.postid,
max(case when t.tagname = 'Incident' then p.value end) Incident,
max(case when t.tagname = 'Location' then p.value end) Location,
max(case when t.tagname = 'Weapon' then p.value end) Weapon
from triples p
left join tags t
on p.tagid = t.id
group by p.postid;
See SQL Fiddle with Demo
But if you have an unknown number of columns, then you will need to use a prepared statement to generate dynamic SQL:
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(CASE WHEN TagName = ''',
TagName,
''' THEN p.value END) AS `',
TagName, '`'
)
) INTO #sql
FROM tags;
SET #sql
= CONCAT('SELECT p.postid, ', #sql, '
from triples p
left join tags t
on p.tagid = t.id
group by p.postid');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
See SQL Fiddle with Demo.
Both will give the result:
| POSTID | INCIDENT | LOCATION | WEAPON |
----------------------------------------------
| 1 | Murder | New Brunswick | (null) |
| 2 | Theft | (null) | Gun |