Dynamically Pivoting Table Data | mySQL - mysql

Essentially I have a table in my database called Table1 with the following data:
The table has a ProductID that repeats because the values of AssignedColour, ColourFinding and ColourPower vary.
I would like to present all ProductID data in one single row, meaning if there is more than one AssignedColour, ColourFinding and ColourPower listed, it will contain a number at the end.
The final result I of the SELECT query should look like the following:
The number of columns presented horizontally is based on the number of AssignedColour per ProductID
Is something like this possible to accomplish in a mySQL SELECT Query?

An SQL query cannot expand the number of columns of the result set depending on the data values it discovers during query execution. The columns in the SELECT-list must be fixed at the time the query is prepared, before it reads any data.
Also the column names cannot be changed during the query execution. They must be set at the time the query is prepared.
There's no way to do what you are describing in a single SQL query. Your options are:
Do two queries: one to enumerate the colors per product, and then use the result of the first to format a second query with the columns you want.
Do one query to fetch the data in rows as it exists in your table, then write code in your app to display it in rows however you think is best.
Either way, you have to write at least a bit of code in the client. You can't do this in one query.

Related

SQL STATEMENT Values getting multiplied by 3

SUM(ISNULL(FlagHrs,0.00) + ISNULL(BackFlagSoldHrs,0.00)) AS Ttl_EmpFlagHrs
Using this statement in a select statement but the values I am getting in Ttl_EmpFlagHrs are getting multiplied by 3, Flaghrs and BackFlaghrs are the different columns present in a certain table.
Since there is no sample data or full query, you are forcing us to answer based on speculation.
Based on your question, Objective is to add FlagHrs and BackFlagSoldHrs and when its null, count it as zero.
Since you are using SUM function, which is a group function, result of multiple rows will be added and presented as a single value.
Based on your question, it is highly likely that, single row is repeated 3 times (could be result of a join) and hence sum is showing up as 3 times.
You can verify this by removing SUM function and checking rows actually selected as result of your query.
Solution:
Verify Join condition to ensure correct rows are selected in your query
If theory of adding it up multiple times is true, you can use AVG function in place of SUM function, the result will be equivalent of single row (rather than 3x)
See if you need to use DISTINCT keyword to remove duplicate rows (if its not desired result)

SQL discrepancy using COUNT command

I am trying to do my first steps with SQL. Currently I am trying to analyse a database and stepped over a problem which I can't explain. Eventually someone could give me a hint.
I have a mySQL table ('cap851312') witch has 330.178 table rows. I already imported the table to Excel, and verified this number!
Every single row includes a field (column 'ID_MES_ANO') for the entries date. For the time being, all the date is uniquely set "201312".
Starting the following command, I would expect to see as a result the given number of rows, however the number which appears is 476.598.
SELECT movedb.cap851312.ID_MES_ANO, count(*)
FROM movedb.cap851312;
I already imported the file to Excel, and verified the number of lines. Indeed, it is 330.178!
How could I find out, what exactly is going wrong?
Update:
I've tried:
SELECT count(*) FROM movedb.cap851312
This returns as well 476.598.
As I am using workbench, I easily could confirm the numer of 330.178 table rows.
Update 2:
The Workbench Table Inspector confirms: "Table rows: 330178"
Solved - However unsure why:
I changed the statement to
SELECT count(ID_MES_ANO) FROM movedb.cap851512;
This time the result is 330178 !
COUNT(*) counts all rows.
COUNT(ID_MES_ANO) counts only rows for which ID_MES_ANO is not null.
So the difference between the two are the rows where ID_MES_ANO is null.
You can verify this with
SELECT count(*) FROM movedb.cap851512 WHERE ID_MES_ANO IS NULL;
By the way:
SELECT movedb.cap851312.ID_MES_ANO, count(*) FROM movedb.cap851312;
means: aggregate all rows to one single result row (by using the aggregate function COUNT without GROUP BY). This result row shows ID_MES_ANO and the number of all records. Standard SQL does not allow this, because you don't tell the DBMS which ID_MES_ANO of those hundreds of thousands of records to show. MySQL violates the standard here and simply picks one ID_MES_ANO arbitrarily from the rows.

Calculate sum from MySQL server or from application

I have a MySQL table which has two columns : ID and count. It has an index on ID field.
Now if i have to get sum of all the count between two IDs, I can write a query like:
Select SUM(count) from table where id between x and y
or i can get
select count from table where id between x and y
And then loop through the result and calculate the sum of the count on my application code
Which one is better, considering the speed is the essential thing here. Will indexing on the count help?? Or can i write a different SQL?
Would indexing on the count column help in any way?
I have around 10000 requests per second coming in and I am using a load balancer and 5 servers for this.
The second one is the correct one. There's no need to sum a count, as the count comes back as a single value. It only needs to be run once.
Unless you have a column named count, in which you want to sum all the values...
EDIT
Because you are saying you have a column named Count, you would use the first query:
Select SUM(count) from table where id between x and y
Use approach 1 as you would save on fetching data from MySQL and iterating over it.
The time taken by MySQL to execute either of your queries would be nearly the same but the second approach would require looping through the results and summing them; unnecessary overhead.

MS Access SQL Unequal join for 3 or more tables

I'm thinking of switching to using temp tables and vba.
I want to do this. I have multiple tables, in these tables may or may not have fields with items that have a one to many or one to one relationship. I know what those relationships are (and will create multiple queries accordingly). What I'm hunting for is each value that DOES NOT EXIST in every other table. To make an example:
Say we have 3 single column tables, table 1 is {x, y, z}, table 2 is {a, x, z}, and table 3 is {a,b,x,y,z}, the result will be b for t3 (yes I need to know where the error is). Pretty much, I want to use the unequal wizard but for 3 or more tables.
I may want to look for any item that exists in some but not all other tables. If you want to speak on that, it would be helpful, but I think that is strictly in the vba realm.
I think the challenge here is the open-endedness of the problem you are trying to solve. Varying column names, table names, and uniqueness thresholds across all tables would make it a bit more difficult. In the way I show below, I don't think it would be the most efficient, query-wise, but would be relatively easy to script. The following code assumes values in the tables are unique within each table.
There are 3 queries total:
qry_001_TableValues_ALL
SELECT Table1.MyValue, "Table1" AS Source
FROM Table1
UNION
SELECT Table2.MyValue, "Table2" AS Source
FROM Table2
UNION SELECT Table3.MyValue, "Table3" AS Source
FROM Table3;
qry_002_TableValues_Unique:
SELECT qry_001_TableValues_ALL.MyValue
FROM qry_001_TableValues_ALL
GROUP BY qry_001_TableValues_ALL.MyValue
HAVING (((Count(qry_001_TableValues_ALL.MyValue))=1));
qry_003_TableValues_UniqueWithSource:
SELECT qry_002_TableValues_Unique.MyValue, qry_001_TableValues_ALL.Source
FROM qry_002_TableValues_Unique INNER JOIN qry_001_TableValues_ALL
ON qry_002_TableValues_Unique.MyValue = qry_001_TableValues_ALL.MyValue;
The first table is the one you would need to script out if columns\tables changed. It is looking across all tables and creating a unique list of values from the specified field. The second query looks to look up the Source table name against the original unique value query for all values which have a count of 1, post aggregation. This means of all tables involved, there is only one instace of the values returned, and it joins against the original unique value list again to determine what the source table is. You can script a change to the HAVING clause here to see if there are x tables which contain the value. The final query is simply the one you run to give you the final report of the values you are looking for and where they reside.
Hope this is in the ballpark of what you are trying to do.

Best way to combine multiple advanced mysql select queries

I have multiple select statements from different tables on the same database. I was using multiple, separate queries then loading to my array and sorting (again, after ordering in query).
I would like to combine into one statement to speed up results and make it easier to "load more" (see bottom).
Each query uses SELECT, LEFT JOIN, WHERE and ORDER BY commands which are not the same for each table.
I may not need order by in each statement, but I want the end result, ultimately, to be ordered by a field representing a time (not necessarily the same field name across all tables).
I would want to limit total query results to a number, in my case 100.
I then use a loop through results and for each row I test if OBJECTNAME_ID (ie; comment_id, event_id, upload_id) isset then LOAD_WHATEVER_OBJECT which takes the row and pushes data into an array.
I won't have to sort the array afterwards because it was loaded in order via mysql.
Later in the app, I will "load more" by skipping the first 100, 200 or whatever page*100 is and limit by 100 again with the same query.
The end result from the database would pref look like "this":
RESULT - selected fields from a table - field to sort on is greatest
RESULT - selected fields from a possibly different table - field to sort on is next greatest
RESULT - selected fields from a possibly different table table - field to sort on is third greatest
etc, etc
I see a lot of simpler combined statements, but nothing quite like this.
Any help would be GREATLY appreciated.
easiest way might be a UNION here ( http://dev.mysql.com/doc/refman/5.0/en/union.html ):
(SELECT a,b,c FROM t1)
UNION
(SELECT d AS a, e AS b, f AS c FROM t2)
ORDER BY a DESC