MySQL - displaying AVG on more than just one row - mysql

If I run a query that includes an Aggregation function (AVG), is there any way I can get that to display on multiple rows? The query I need would be something like:
SELECT field1, field2, AVG(field2) FROM tMyTable;
The output I need would be something like:
field 1 | field 2 | AVG(field2)
record1 | 1.17 | 1.19
record2 | 1.21 | 1.19
record3 | 1.18 | 1.19
As you can see, I need the average output to be displayed on each and every line. I appreciate that this may be/is an unorthodox approach, however that output format is needed for a charting app that I use.
If there are any methods available then I'd be grateful for your suggestions. Perhaps nesting a second lookup?

SELECT field1,field2,(SELECT AVG(field2) FROM Table) AS AvgFieldTwo
FROM Table

You can also use a CROSS JOIN:
SELECT field1, field2, src.AvgField2
FROM MyTable
CROSS JOIN
(
SELECT avg(field2) AvgField2
FROM MyTable
) src

Related

Union as sub query using MySQL 8

I'm wanting to optimize a query using a union as a sub query.
Im not really sure how to construct the query though.
I'm using MYSQL 8.0.12
Here is the original query:
---------------
| c1 | c2 |
---------------
| 18182 | 0 |
| 18015 | 0 |
---------------
2 rows in set (0.35 sec)
I'm sorry but the question doesn't stored if I paste the sql query as text and format using ctrl+k
Output expected
---------------
| c1 | c2 |
---------------
| 18182 | 167 |
| 18015 | 0 |
---------------
As a output I would like to have the difference of rows between the two tables in UNION ALL.
I processed this question using the wizard https://stackoverflow.com/questions/ask
Since a parenthesized SELECT can be used almost anywhere a expression can go:
SELECT
ABS( (SELECT COUNT(*) FROM tbl_aaa) -
(SELECT COUNT(*) FROM tbl_bbb) ) AS diff;
Also, MySQL is happy to allow a SELECT without a FROM.
There are several ways to go for this, including UNION, but I wouldn't recommend it, as it is IMO a bit 'hacky'. Instead, I suggest you use subqueries or use CTEs.
With subqueries
SELECT
ABS(c_tbl_aaa.size - c_tbl_bbb.size) as diff
FROM (
SELECT
COUNT(*) as size
FROM tbl_aaa
) c_tbl_aaa
CROSS JOIN (
SELECT
COUNT(*) as size
FROM tbl_bbb
) c_tbl_bbb
With CTEs, also known as WITHs
WITH c_tbl_aaa AS (
SELECT
COUNT(*) as size
FROM tbl_aaa
), c_tbl_bbb AS (
SELECT
COUNT(*) as size
FROM tbl_bbb
)
SELECT
ABS(c_tbl_aaa.size - c_tbl_bbb.size) as diff
FROM c_tbl_aaa
CROSS JOIN c_tbl_bbb
In a practical sense, they are the same. Depending on the needs, you might want to define and join the results though, and in said cases, you could use a single number as a "pseudo id" in the select statement.
Since you only want to know the differences, I used the ABS function, which returns the absolute value of a number.
Let me know if you want a solution with UNIONs anyway.
Edit: As #Rick James pointed out, COUNT(*) should be used in the subqueries to count the number of rows, as COUNT(id_***) will only count the rows with non-null values in that field.

MySQL select column name and value as a field

I have a mysql table that looks something like this:
id | PO | DAP | MEDIA
---|----|-------|------
1 | 2 | 34 | 64
2 | 6 | 53 | 23
I would like to be able to query get multiple rows, one for each column. E.g:
SELECT column_name as column, column_value as value FROM my_table;
Which would give me:
PO=2,DAP=34,MEDIA=54,PO=6,DAP=53,MEDIA=23
What would I need to use to formulate a query like this?
You have to first CONCAT the data of each specified field and apply GROUP_CONCAT ON the result.
Query
SELECT GROUP_CONCAT(temp_col) FROM
(
SELECT 1 as 'temp_id',
CONCAT(
CONCAT('PO=', PO),
',',
CONCAT('DAP=', DAP),
',',
CONCAT('MEDIA=', MEDIA)
) AS 'temp_col'
FROM test
) temp
GROUP BY temp_id
Check Out SQLFIDDLE
Not exactly sure what you mean. But this is traditionally done in this manner
SELECT * FROM my_table;
You'll get your array like this
array(0=>array('PO'=>2,'DAP'=>34,'MEDIA'=54), 1=>array('PO'=>6, 'DAP'=>53, 'MEDIA'=> 23))
.. like so.

MySQL - Including the results of a procedure in a select statement

I have a table, called gcrunarrays with the columns {run_id, time_id, co2}. I have several thousand runs with distinct run_id's, each with 58 time-dependent values for co2. I have a procedure to obtain the median co2 of all runs at a given time. Now, I need a select statement that will obtain the medians for each time. So far, I have
select DISTINCT A.time_id, M.co2 from gcrunarrays A, call getMedian(1, A.time_id) M
GO
Which gets a syntax error. I am fairly new at SQL and I'm working in MYSQL. I've tried about a dozen different ways of wording this statement but now I'm at the point where I feel like I've done something inherently wrong. I think it might work better if median were a function but I'm not sure even how to get the median without using a select statement. Any suggestions are greatly appreciated.
For greater clarification:
Table gcrunarrays
run_id | time_id | co2
1 | 1 |
1 | 2 |
...
1 | 58 |
2 | 1 |
...
2 | 58 |
3 ...
Median Procedure
CREATE PROCEDURE getMedian (IN e INT, t INT)
BEGIN
SELECT count(*), x.co2
FROM (SELECT B.exp_id, A.* FROM gcRunArrays A JOIN gcRuns B ON A.run_id=B.run_id WHERE B.exp_id=e and A.time_id=t) x,
(SELECT B.exp_id, A.* FROM gcRunArrays A JOIN gcRuns B ON A.run_id=B.run_id WHERE B.exp_id=e and A.time_id=t) y
GROUP BY x.co2
HAVING SUM(SIGN(1-SIGN(y.co2-x.co2))) = CEILING((COUNT(*)+1)/2);
END
GO
Use a temp table can easily solve the issue.
And it is not possible to use procedure results as table directly.
Can a stored procedure/function return a table?

Mysql-Select all tables from a database

I've a database called test and i've tables called x,y,z.
How do i select x,y,z and there is a column called date IN X,Y,Z check whether there is a particular date.
Is there any build in function that does this?
update
SELECT column date from all tables which is in a database called test
Thanks in advance!!
As far as I know, in SQL you cannot 'select a table', you can select some
column(s) from one or many tables at once. The result of such a query is an another table (temporary table) that you retrieve the data from.
Please be more specific about what exactly you want to do (e.g.: "I want to select a column 'z' from table 'tableA' and column 'y' from table 'tableB'") - then I'm sure your question has a pretty simple answer :)
SELECT x.date AS x_date, y.date AS y_date, z.date AS z_date FROM x,y,z;
That produces a result:
+---------+---------+---------+
| x_date | y_date | z_date |
+---------+---------+---------+
| | | |
| | | |
+---------+---------+---------+
Alternatively you can get everything in one column by ussuing a query:
SELECT date FROM x
UNION ALL
SELECT date FROM y
UNION ALL
SELECT date FROM z;
That produces a result:
+-------+
| date |
+-------+
| |
| |
+-------+
In the example above you would get also duplicate values in the single column. If you want to avoid duplicates replace 'UNION ALL' with 'UNION'
I'm still not sure if I undestood what you really want ot achieve, but I still hope that helps
Also take a look at:
http://www.w3schools.com/sql/sql_union.asp
http://www.sql-tutorial.net/SQL-JOIN.asp

MySQL SUM when using GROUP BY not working

Let's say we have this table:
Symbol | Size
A | 12
B | 5
A | 3
A | 6
B | 8
And we want a view like this:
Symbol | Size
A | 21
B | 13
So we use this:
Select Symbol, sum(Size) from table group by Symbol order by Symbol ASC
But instead we get this:
Symbol | Size
A | 12
B | 5
What am I doing wrong?!
You are doing it right, you should expect the correct results. Could you please supply more information about the DB you are using, additional schemas, etc?
Maybe you have some unique index on Symbol?
Try to execute the following to "sanity-test" your system:
SELECT SUM(Size) FROM table
Should result in 34
SELECT Symbol, Count(*) FROM table GROUP BY Symbol
Should results in 3 and 2
If both of the above work perfectly as you noted, please try:
SELECT Symbol, Count(*), Sum(Size) FROM table GROUP BY Symbol
This is your code, with the additions of Count(*) and without the ORDER BY clause. If that does not work after the two above do, I'm really puzzled...
I found out that somewhere in the Select commands that leaded to the Un-SUMable table instead of a left join there was a simple join.Although I still don't get why that should mess up the calculation, I changed that and now it works... I'm sorry I couldn't upload the whole thing...