How change colums for rows in a query - mysql

I have a survey with many objectives for assess from 1 to 5 in my web page. I send the survey to my database in my table of survey.
For example
obj1value | obj2value | obj3value ... | obj17value |
I have a value for every survey.
Now I need to do some charts for present a report of the survey.
I need to add up the totals for each objective.
I have this query
SELECT SUM(obj1_value) AS objective1, SUM(obj2_value) AS objective2, SUM(obj3_value) AS objective3, FROM tbl_survey
I have this till objective17 and the query returns
| objective1 | objective2 | objective3 |
| --- | --- | --- |
| 17 | 12 | 5 |
But I need to change the query like this
_objective_ | _Value_
objective1 | 17
objective2 | 12
objective3 | 5
Objective17 | n
Someone can help me with the query to optimize because in this way I can convert the table php in json and took a bar chart library so easy.
Thank you

It is probably easiest to do the transformation in PHP. One method in MySQL is a simple UNION ALL:
SELECT 'obj1_value', SUM(obj1_value)
FROM tbl_survey
UNION ALL
SELECT 'obj2_value', SUM(obj2_value)
FROM tbl_survey
UNION ALL
. . .
The downside to this approach is that the table is scanned 17 times, so it will probably take about 17 times as long.
You can improve performance by doing an unpivot. Here is one method in MySQL:
SELECT o.obj,
(CASE WHEN obj = 'objective1' THEN objective1
WHEN obj = 'objective2' THEN objective2
. . .
END) as value
FROM (SELECT SUM(obj1_value) AS objective1, SUM(obj2_value) AS objective2,
SUM(obj3_value) AS objective3, . . .
FROM tbl_survey
) s CROSS JOIN
(SELECT 'objective1' as obj UNION ALL
SELECT 'objective2' as obj UNION ALL
. . .
) o;

the solution for this problem is PIVOT AN UNPOVIT , and you can change the out put us you want , this is tutorial can help you

Related

Implementing SUMIF() function from Excel to SQL

Lately, I have been learning how to use SQL in order to process data. Normally, I would use Python for that purpose, but SQL is required for the classes and I still very much struggle with using it comfortably in more complicated scenarios.
What I want to achieve is the same result as in the following screenshot in Excel:
Behaviour in Excel, that I want to implement in SQL
The formula I used in Excel:
=SUMIF(B$2:B2;B2;C$2:C2)
Sample of the table:
> select * from orders limit 5;
+------------+---------------+---------+
| ID | clientID | tonnage |
+------------+---------------+---------+
| 2005-01-01 | 872-13-44-365 | 10 |
| 2005-01-04 | 369-43-03-176 | 2 |
| 2005-01-05 | 408-24-90-350 | 2 |
| 2005-01-10 | 944-16-93-033 | 5 |
| 2005-01-11 | 645-32-78-780 | 14 |
+------------+---------------+---------+
The implementation is supposed to return similar results as following group by query:
select
orders.clientID as ID,
sum(orders.tonnage) as Tonnage
from orders
group by orders.clientID;
That is, return how much each client have purchased, but at the same I want it to return each step of the addition as separate record.
For an instance:
Client A bought 350 in the first order and then 231 in the second one. In such case the query would return something like this:
client A - 350 - 350 // first order
client A - 281 - 581 // second order
Example, how it would look like in Excel
I have already tried to use something like:
select
orders.clientID as ID,
sum(case when orders.clientID = <ID> then orders.tonnage end)
from orders;
But got stuck quickly, since I would need to somehow dynamically change this <ID> and store it's value in some kind of temporary variable and I can't really figure out how to implement such thing in SQL.
You can use window function for running sum.
In your case, use like this
select id, clientID, sum(tonnage) over (partition by clientID order by id) tonnageRunning
from orders
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=13a8c2d46b5ac22c5c120ac937bd6e7a

Count substrings in SQL (in Digital Metaphors' ReportBuilder)

I'm trying to create a report in ReportBuilder (Digital Metaphors, not Microsoft) and I'm having trouble getting the SQL to do what I want.
I have one table with a field building:
| building |
+------------+
| WhiteHouse |
| TajMahal |
and another table with a field locations:
| id | locations |
+----+-----------------------------------------------------------------+
| 1 | WhiteHouse:RoseGarden,WhiteHouse:MapRoom,TajMahal:MainSanctuary |
| 2 | TajMahal:NorthGarden,WhiteHouse:GreenRoom |
I would like to create a table showing how many times each building is used in locations, like so:
| building | count |
+------------+-------+
| WhiteHouse | 3 |
| TajMahal | 2 |
The characters : and , are never used in building or room names. Even a quick-and-dirty solution that assumes that building names never appear in room names would be good enough for me.
Of course this would be easy to do in just about any sane programming language (total over something like /\bWhiteHouse:/); the trick will be getting RB to do it. Suggestions for workarounds are welcome.
it is possible to split locations string into pieces using the "," and ":" characters as seperators as follows in SQL Server with the help of a custom sql split function
select
p2.val,
count(p2.val)
from locations l
cross apply dbo.split(l.locations,',') p1
cross apply dbo.split(p1.val,':') p2
inner join building b
on b.building = p2.val
group by p2.val
I'm not sure there is a similar one in mysql, if so please check following solution as a template
You can try this, probably not the fastest, but certainly easier solution.
SELECT t1.building,
( SELECT SUM( ROUND( (LENGTH(t2.locations)
- LENGTH(REPLACE(t2.locations, concat(t1.building, ':'), ''))
) / (LENGTH(t1.building) + 1)
)
)
FROM table2 AS t2
) as count
FROM table1 as t1
SQL Fiddle Demo

how to sum amount based on 2 columns that are both dates in mysql

i have a tbl_remit where i need to get the last remittance.
I'm developing as system wherein I need to get the potential collection of each Employer using the Employer's last remittance x 12. Ideally, Employers should remit once every month. But there are cases where an Employer remits again for the same month for the additional employee that is newly hired. The Mysql Statement that I used was this.
SELECT Employer, MAX(AP_From) as AP_From,
MAX(AP_To) as AP_To,
MAX(Amount) as Last_Remittance,
(MAX(Amount) *12) AS LastRemit_x12
FROM view_remit
GROUP BY PEN
Result
|RemitNo.| Employer | ap_from | ap_to | amount |
| 1 | 1 |2016-01-01 |2016-01-31 | 2000 |
| 2 | 1 |2016-02-01 |2016-02-28 | 2000 |
| 3 | 1 |2016-03-01 |2016-03-31 | 2000 |
| 4 | 1 |2016-03-01 |2016-03-31 | 400 |
By doing that statement, i ended up getting the wrong potential collection.
What I've got:
400 - Last_Remittance
4800 - LastRemit_x12 (potential collection)
What I need to get:
2400 - Last_Remittance
28800 - LastRemit_x12 (potential collection)
Any help is greatly appreciated. I don't have a team in this project. this may be a novice question to some but to me it's really a complex puzzle. thank you in advance.
You want to filter the data for the last time period. So, think where rather than group by. Then, you want to aggregate by employer.
Here is one method:
SELECT Employer, MAX(AP_From) as AP_From, MAX(AP_To) as AP_To,
SUM(Amount) as Last_Remittance,
(SUM(Amount) * 12) AS LastRemit_x12
FROM view_remit vr
WHERE vr.ap_from = (SELECT MAX(vr2.ap_from)
FROM view_remit vr2
WHERE vr2.Employer = vr.Employer
)
GROUP BY Employer;
EDIT:
For performance, you want an index on view_remit(Employer, ap_from). Of course, that assumes that view_remit is really a table . . . which may be unlikely.
If you want to improve performance, you'll need to understand the view.

MySQL special case pivot

I cant find an answer to this despite looking for several days!
In MySQL I have 2 Tables
ProcessList contains foreign keys all from the process Table
ID |Operation1|Operation2|Operation3|etc....
---------------------------------------
1 | 1 | 4 | 6 | ....
---------------------------------------
2 | 2 | 4 | 5 |....
---------------------------------------
.
.
.
Process Table
ID | Name
-------------------
1 | Quote
2 | Order
3 | On-Hold
4 | Manufacturing
5 | Final Inpection
6 | Complete
Now, I am new to SQL but I understand that MYSQL doesnt have a pivot function as Ive researched, and I see some examples with UNIONs etc, but I need an SQL expression something like (pseudocode)
SELECT name FROM process
(IF process.id APPEARS in a row of the ProcessList)
WHERE processListID = 2
so I get the result
Order
Manufacturing
Final Inspection
I really need the last line of the query to be
WHERE processListID = ?
because otherwise I will have to completely rewrite my app as the SQL is stored in a String in java, and the app suplies the key index only at the end of the statement.
One option is using union to unpivot the processlist table and joining it to the process table.
select p.name
from process p
join (select id,operation1 as operation from processlist
union all
select id,operation2 from processlist
union all
select id,operation3 from processlist
--add more unions as needed based on the number of operations
) pl
on pl.operation=p.id
where pl.id = ?
If you always consider only a single line in the process list (i.e. procsessListId = x), the following query should do a pretty simple and performant job:
select p.name from process p, list l
where l.id = 2
and (p.id in (l.operation1, l.operation2, l.operation3))

SQL select data from multiple tables

I'm trying to select from multiples tables(10+) that are in the following format using mySQL.
+----------table(n)-----------+
+-----------------------------+
| url | id | ... |
+-----------+-----------+-----+
| url1.com | 12345678 | ... |
| url2.com | 45832458 | ... |
What I need to do is retrieve the id from each table for a given URL and return it in a single row like so.
+--------------table(n)--------------+
+------------------------------------+
| url | table(n) | table(n+1) |
+-----------+-----------+------------+
| url1.com | 12345678 | 8182735 |
But the URL might not exist for a given table, so I just need to retrieve all the ids from the tables where the URL is found.
For example, I have 10 tables and a URL/id is in 4 of them. I need to retrieve these 4, in a single row. I've tried to use aliases for columns along with various JOIN combinations to no avail.
Any help would be appreciated.
You can do this with a union all and group by:
select url,
max(id1) as id1, max(id2) as id2, . . .
from ((select url, id as id1, NULL as id2, . . . from table1) union all
(select url, NULL as id1, id as id2, . . . from table1) union all
. . .
) t
group by url;
try like this
SELECT tu.URL,COALESCE(table_1.id,0) AS table_1,COALESCE(table_2.id,0) As
table_2,......,COALESCE(table_n.id,0) AS table_n FROM Table_URL tu
LEFT JOIN table_1 ON tu.URL = table_1.URL
LEFT JOIN table_2 ON tu.URL = table_2.URL
.
.
LEFT JOIN table_n ON tu.URL = table_n.URL
You want a variable number of columns generated by your SQL statement, and you cannot do that with MySQL.
You can see some techniques to get around it here: MySQL pivot row into dynamic number of columns
Many reporting tools will let you do things like you want to, but using some sort of prepared statement hack with MySQL would be the only way to do it:
http://buysql.com/mysql/14-how-to-automate-pivot-tables.html