MySql: Calculate a value based on multiple sub-queries - mysql

I have a query that calculates a value based on several sub-queries. The sub-queries are based on a specific timestamp. I would like to calculate this value for records for many different timestamps. I can't quite figure out how to do it.
The basic formula is (S11S4CreateSessionReqRcvd - S11S4CreateSessionRespAccSent) * 100 / S11S4CreateSessionRespAccSent
SELECT
((((select ref_data FROM test.sgw_S5S11 where timestamp = "2013-08-21 00:00:06" and ref_type = "S11S4CreateSessionReqRcvd" ) - (select ref_data FROM test.sgw_S5S11
where timestamp = "2013-08-21 00:00:06" and ref_type = "S11S4CreateSessionRespAccSent")) * 100) / (select ref_data FROM test.sgw_S5S11
where timestamp = "2013-08-21 00:00:06" and ref_type = "S11S4CreateSessionReqRcvd")) as MyCalc
I don't know how to paste in a table so here's a sample of my data in csv format
Here's a sample of my data. (I don't know how to put a table in here so it's in CSV format)
mykey,timestamp,ref_type,ref_data 1016101,"2013-08-21 00:00:06",S5S8CreateSessionReqSent,128042907 1016102,"2013-08-21 00:00:06",S5S8CreateSessionRespAccRcvd,127088838 1016103,"2013-08-21 00:00:06",S5S8CreateSessionRespRejRcvd,615553 1016104,"2013-08-21 00:00:06",S5S8CreateBearerReqRcvd,10047 1016105,"2013-08-21 00:00:06",S5S8CreateBearerRespAccSent,9932 1016106,"2013-08-21 00:00:06",S5S8CreateBearerRespRejSent,103 1016107,"2013-08-21 00:00:06",S11S4CreateSessionReqRcvd,128255390 1016108,"2013-08-21 00:00:06",S11S4CreateSessionRespAccSent,127114539 1016109,"2013-08-21 00:00:06",S11S4CreateSessionRespRejSent,713325 1016110,"2013-08-21 00:00:06",S11S4CreateBearerReqSent,10028 1016111,"2013-08-21 00:00:06",S11S4CreateBearerRespAccRcvd,9932 1016112,"2013-08-21 00:00:06",S11S4CreateBearerRespRejRcvd,42
Any help would be greatly appreciated!!!

This query is awkward because you have stored attributes on separate rows. This design is called Entity-Attribute-Value, and it's usually a bad idea for a relational database.
The following query might be a little more efficient and easier to write:
SELECT (eav.ReqRcvd - eav.AccSent) * 100 / eav.AccSent AS MyCalc
FROM (
SELECT timestamp,
MAX(IF(ref_type='S11S4CreateSessionReqRcvd', ref_data)) AS ReqRcvd,
MAX(IF(ref_type='S11S4CreateSessionRespAccSent', ref_data)) AS AccSent
FROM test.sgw_S5S11
WHERE timestamp = '2013-08-21 00:00:06'
GROUP BY timestamp
) AS eav;
PS: Use single quotes ' for string and date literals, not double quotes ". In standard SQL, double quotes are for delimiting table and column identifiers. MySQL treats the two types of quotes the same by default, but this is subject to SQL_MODE and also won't behave the same way if you ever use another brand of RDBMS. So it's a good to develop the habit of using quotes in the standard way.

Related

MySQL returns all rows when field=0 from SECOND Select query

This case is similar to: S.O Question; mySQL returns all rows when field=0, and the Accepted answer was a very simple trick, to souround the ZERO with single quotes
FROM:
SELECT * FROM table WHERE email=0
TO:
SELECT * FROM table WHERE email='0'
However, my case is slightly different in that my Query is something like:
SELECT * FROM table WHERE email=(
SELECT my_column_value FROM myTable WHERE my_column_value=0 AND user_id =15 LIMIT 1 )
Which in a sense, becomes like simply saying: SELECT * FROM table WHERE email=0, but now with a Second Query.
PLEASE NOTE: It is a MUST that I use the SECOND QUERY.
When I tried: SELECT * FROM table WHERE email='( SELECT my_column_value FROM myTable WHERE my_column_value=0 LIMIT 1 )' (Notice the Single Quotes on the second query)
MySql SCREAMED Errors near '(.
How can this be achieved
Any Suggestion is highly honored
EDIT1: For a visual perspective of the Query
See the STEN_TB here: http://snag.gy/Rq8dq.jpg
Now, the main aim is to get the sten_h where rawscore_h = 0;
The CURRENT QUERY as a whole.
SELECT sten_h
FROM sten_tb
WHERE rawscore_h = (
SELECT `for_print_stens_rowscore`
FROM `for_print_stens_tb`
WHERE `for_print_stens_student_id` =3
AND `for_print_stens_factor_name` = 'Factor H' )
The result of the Second Query can be any number including ZERO.
Any number from >=1 Works and returns a single corresponding value from sten_h. Only =0 does not Work, it returns all rows
That's the issue.
CORRECT ANSWER OR SOLUTION FOR THIS
Just in case someone ends up in this paradox, the Accepted answer has it all.
SEE STEN_TB: http://snag.gy/Rq8dq.jpg
SEE The desired Query result here: http://snag.gy/wa4yA.jpg
I believe your issue is with implicit datatype conversions. You can make those datatype conversions explicit, to gain control.
(The "trick" with wrapping a literal 0 in single quotes, that makes the literal a string literal, rather than a numeric.)
In the more general case, you can use a CAST or CONVERT function to explicitly specify a datatype conversion. You can use an expression in place of a column name, wherever you need to...
For example, to get the value returned by my_column_value to match the datatype of the email column, assuming email is character type, something like:
... email = (SELECT CONVERT(my_column_value,CHAR(255)) FROM myTable WHERE ...
or, to get the a literal integer value to be a string value:
... FROM myTable WHERE my_column_value = CONVERT(0,CHAR(30)) ...
If email and my_column_value are just indicating true or false then they should almost certainly be both BIT NOT NULL or other two-value type that your schema uses for booleans. (Your ORM may use a particular one.) Casting is frequently a hack made necessary by a poor design.
If it should be a particular user then you shouldn't use LIMIT because tables are unordered and that doesn't return a particular user. Explain in your question what your query is supposed to return including exactly what you mean by "15th".
(Having all those similar columns is bad design: rawscore_a, sten_a, rawscore_b, sten_b,... . Use a table with two columns: rawscore, sten.)

What is the best way to select a rows by comparing ENUM and SET columns

I mean if any table consist of ENUM or SET typed column and I will make the query like:
SELECT * FROM `tabname` WHERE `enum_field` = 'case1' OR `enum_field` = 'case2'
Will it be efficient?
Or the engine will convert number stored in enum_field to string, compare it to the pattern (in my example - case1 and case2)?
What is the most efficient way to use such columns?
Thanks!
The syntax you provided above is correct.
The database engine will convert the strings in your query into numeric indexes, which will be used when searching the table.
According to the mysql documentation, you can also query directly by numeric index, but this can sometimes have unexpected results, particularly if any of your enum string values are numeric.
So assuming "case1" has index 1, and "case2" has index 2, you could rewrite your query like this:
SELECT * FROM `tabname` WHERE `enum_field` = 1 OR `enum_field` = 2

Is OK to enclosing all values in SQL statement with single quotes?

Is it ok to enclose all values in SQL statement with single quotes ? For example:
This is simple table called books:
id | title
1 | Some book name
2 | Second book name
Is it OK to write statement like this:
SELECT * FROM books WHERE id = '1'
I've tested that query in SQL server 2008 and MySQL 5 and it works good, but I am curious is there any performance issue, because ID field is acctualy integer.
And second question is it OK to write statement like this:
SELECT * FROM books WHERE id = N'1'
N prefix is used in SQL server for UTF-8 fields, but I've tested that in SQL server and MySQL and both worked OK. I don't know if SQLite support N prefix, because I didn't test that.
The reason why I am asking this is because I am building database class that will work with popular SQL databases (SQL Server, MySQL, SQLite and maybe MS Access), so when performing selecting, inserting or updating data I don't have to worry about field datatype. I can always enclose value with N'Some value', but I am curious is this correct and is there any performance issues?
In SQL Server, you can get an implicit conversion when doing this. Sometimes it won't affect the plan or have noticeable impacts on performance, but sometimes it might. They are generally deemed to be bad. Inspect the plans for these two queries against AdventureWorks2012:
SELECT * FROM Sales.SalesOrderHeader WHERE SalesOrderID = 43659;
SELECT * FROM Sales.SalesOrderHeader WHERE SalesOrderID = '43659';
The latter contains a CONVERT_IMPLICIT (hover over the tooltip for the CI seek).
You also want to be very careful about switching between VARCHAR and NVARCHAR - in some cases this can be dreadful for performance, depending on the underlying data type and whether the literal has the N prefix.
Long story short: don't do this. Write your ORM thingy so that it understands the different data types and handles them appropriately.
SELECT ... WHERE int_type = '123' is fine to do. SQL will convert '123' to an integer once and be done with it.
However, SELECT ... WHERE char_type = 123 is no okay, because SQL will have to convert every cell into an integer. See that char_type = '0123' and char_type = '00123' will also match. So it has to do more work.
Thanks to #MartinSmith for pointing out a resource for precedence in casting: http://msdn.microsoft.com/en-us/library/ms190309.aspx
Here's an example bug in MySQL that says the implicit typecast from quoted string of digits to an integer causes a severe performance issue: http://bugs.mysql.com/bug.php?id=43319
It's best to not quote numbers.
SQL Server and MySQL both perform implicit type conversions, but it doesn't make it a good practice; use the appropriate native type when you can. This will let you avoid trying to spot the difference between:
SELECT * FROM books WHERE id = '1'
and
SELECT * FROM books WHERE id = 'l'
and
SELECT * FROM books WHERE id = 'O'
and
SELECT * FROM books WHERE id = '0'
(that's a one, a lower case L, a capital 'o', and a zero respectively)

mysql query based on length of string in a column

I am trying to query a table in mysql based on the length of a string in a specific column. I know mysql has a function called LENGTH(), but that returns the length of the string. I want to be able to pull data based on the result of the LENGTH() function.
Example:
SELECT * table WHERE LENGTH(word) = 6
of course that does not work. I read through http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function%5Flength but could not find anything to help me.
yes I could make something in PhP to accomplish this, but I would like to do it at the query level.
Any help?
Try:
SELECT *
FROM table
WHERE LENGTH(RTRIM(word)) = 6
I believe you wanted to use query SELECT * FROM tableName WHERE LENGTH(word) = 6; (assuming that the word is name of column in tableName).
This is very unfortunate solution on large tables, you should create new column and use UPDATE tableName SET wordLength = LENGTH( word).

MySQL Selecting where datetime column =

Hi I am trying to get the following sql to work in mysql but it always return an empty result set - however there are definitely entries that match the criteria.
I'm new to mySQl so would appreciate if someone could point out where I am going wrong.
SELECT * FROM `ch_results`
WHERE 'readingDateTime' = '2011-03-29 20:00:00'
Remove the quotes around the field name:
SELECT *
FROM `ch_results`
WHERE readingDateTime = '2011-03-29 20:00:00'
Your current query compares string 'readingDateTime' to another string, '2011-03-29 20:00:00', which comparison of course never holds true.
Drop the quotes on the 'readingDateTime'. This is comparing strings to each other.
WHERE readingDateTime = '2011-03-29 20:00:00'