mysql query, reuse columnnames in query - mysql

I have a mysql query, something like this:
SELECT users*100 as totalusers, totalusers*90 AS totalsalerys FROM table
As you can see I want to reuse the totalusers when calculating totalsalerys so I son't have to write the same code again. That dosen't seem to work in mysql, is there another easy way to do this?
My query is just an example, change the *100 and *90 to some very long formula and you might see what i mean..

SELECT (#r := users * 100) as totalusers,
#r * 90 AS totalsalerys
FROM table
You can also use a subquery as #Tom Ritter advices, but it's not friendly to ORDER BY ... LIMIT ... clause.
In MySQL, all results of the inner subquery will be fetched before applying any filters in the outer subquery.

I believe you would have to copy/paste the formula or use a subquery. The below would work in T-SQL, but I imagine it'd work in MySQL as well since it's pretty simple.
SELECT
x.totalusers, x.totalusers*90 AS totalsalerys
FROM (
SELECT users*100 as totalusers FROM table
) x

Related

DENSE_RANK() OVER and IFNULL()

Let's say I have a table like this -
id
number
1
1
2
1
3
1
I want to return the second largest number, and if there isn't, return NULL instead. In this case, since all the numbers in the table are the same, there isn't the second largest number, so it should return NULL.
These codes work -
SELECT IFNULL((
SELECT number
FROM (SELECT *, DENSE_RANK() OVER(ORDER BY number DESC) AS ranking
FROM test) r
WHERE ranking = 2), NULL) AS SecondHighestNumber;
However, after I changed the order of the query, it doesn't work anymore -
SELECT IFNULL(number, NULL) AS SecondHighestNumber
FROM (SELECT *, DENSE_RANK() OVER(ORDER BY number DESC) AS ranking
FROM test) r
WHERE ranking = 2;
It returns blank instead of NULL. Why?
Explanation
This is something of a byproduct of the way you are using subquery in your SELECT clause, and really without a FROM clause.
It is easy to see with a very simple example. We create an empty table. Then we select from it where id = 1 (no results as expected).
CREATE TABLE #foo (id int)
SELECT * FROM #foo WHERE id = 1; -- Empty results
But now if we take a left turn and turn that into a subquery in the select statement - we get a result!
CREATE TABLE #foo (id int)
SELECT (SELECT * FROM #foo WHERE id = 1) AS wtf; -- one record in results with value NULL
I'm not sure what else we could ask our sql engine to do for us - perhaps cough up an error and say I can't do this? Maybe return no results? We are telling it to select an empty result set as a value in the SELECT clause, in a query that doesn't have any FROM clause (personally I would like SQL to cough up and error and say I can't do this ... but it's not my call).
I hope someone else can explain this better, more accurately or technically - or even just give a name to this behavior. But in a nutshell there it is.
tldr;
So your first query has SELECT clause with an IFNULL function in it that uses a subquery ... and otherwise is a SELECT without a FROM. So this is a little weird but does what you want, as shown above. On the other hand, your second query is "normal" sql that selects from a table, filters the results, and lets you know it found nothing -- which might not be what you want but I think actually makes more sense ;)
Footnote: my "sql" here is T-SQL, but I believe this simple example would work the same in MySQL. And for what it's worth, I believe Oracle (back when I learned it years ago) actually would cough up errors here and say you can't have a SELECT clause with no FROM.

sql COALESCE result (12300.4567) to 12,300

How to select COALESCE result to format( , 0)
my query is
SELECT (COALESCE((SELECT SUM(`invoices`.`paid_amount`) FROM `invoices`
WHERE DATE(`invoices`.`date`)=CURDATE()),0) +
COALESCE((SELECT SUM(`other_incomes`.`other_income_amount`) FROM `other_incomes`
WHERE DATE(`other_incomes`.`date`)=CURDATE()),0))
AS total
FROM
....
Primarily, COALESCE doesn't change the formatting. It only returns the first non-null value passed to it.
Also, instead of trying to join or do two different queries and adding, and handling all the sums and coalesces separately (not to mention the rounding), I would probably UNION all the relevant results together, then handle the coalesce/sum/round all at the end.
Try this:
SELECT round(sum(coalesce(amt, 0)), 0) as total
FROM (
SELECT paid_amount as amt
FROM invoices i
WHERE date(i.date) = CURDATE()
union all
SELECT other_income_amount
FROM other_incomes o
WHERE date(o.date) = CURDATE()
) z
Here I COALESCE first, to make nulls be 0 instead. I wrap that in a SUM to add up the values, and finally a ROUND to get the format. It was unclear from the question is you wanted to ROUND or FLOOR. If you are looking to get it with that comma, use FORMAT. Here's the mySQL documentation for that. You didn't specify your SQL flavor.
https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_format
Additionally, you should include your sql platform and version, the create statements for your tables, along with some insert statements that will provide sample data, along with the results you are looking for. It will help people answer your question. If you can include a fiddle, like https://dbfiddle.uk/, that would be nice.

How to SELECT COUNT(DISTINCT) and WHERE conditional on Ms.Access Query

I just wanted to simply count using where conditional and yet this query ask me for parameter instead of automatically execute the query
SELECT COUNT(ActDiscDischargingPort) from(
SELECT DISTINCT ActDiscDischargingPort FROM SelisihLoadVSActualLoadTable) WHERE SchLoadVessel LIKE "XB24 - MV. MEMPHIS" AND SchLoadVoyageNo LIKE "0019";
What is the proper way of writing this query?
Found the answer, turn out the query has to be like this
SELECT COUNT(ActDiscDischargingPort) from ( SELECT DISTINCT ActDiscDischargingPort FROM SelisihLoadVSActualLoadTable WHERE SchLoadVoyageNo LIKE "XB24 - MV. MEMPHIS" AND SchLoadVessel LIKE "0019" )
Every derived table must have its own alias.
The correct syntax would be
SELECT
COUNT(ActDiscDischargingPort)
from(
SELECT
DISTINCT ActDiscDischargingPort
FROM
SelisihLoadVSActualLoadTable
) AS T
WHERE
SchLoadVessel LIKE "XB24 - MV. MEMPHIS"
AND SchLoadVoyageNo LIKE "0019";
You can further speed up your query by optimizing it a bit.

SQL Assign "co-efficients" to query conditions and use them to sort result

I saw a query once that assigned some kind of ranking to query conditions, I can't remember it now.
They way I understood it, i think variable names (s1,s2,...) were assigned to each of the conditions with a coefficient to give them different "weights" then the sum of the variables was used to sort the result.
It looked something like this:
SELECT
*
FROM
table_name
WHERE condition1='value1' as (s1*3)
OR condition2='value2' as (s2*2)
OR condition3='value3' as (s3*1)
ORDER BY (s1+s2+s3)
So, the different numbers sort of give the conditions varying degrees of importance in the ORDER, makes it perfect for doing a related product/post search.
Please, does anyone know the right structure for this query?
In MySQL, you would define the aliases in the SELECT clause and then use them in the ORDER BY. For instance:
SELECT t.*, (condition1 = 'value1') as s1,
(condition2 = 'value2') as s2, (condition3 = 'value3') as s3
FROM table t
ORDER BY (s1*3 + s2*2 + s3*1);

AS not working with COUNT(*) and UNION

So I have joined 3 queries together using UNIONs and want to count the number of lines in the result, but it's a bit weird. It actually works, and gives the correct answer, but it doesn't assign the "AS" part correctly.
SELECT COUNT(*) FROM (
(Long Select Statement)
UNION
(AnotherLong Select Statement)
UNION
(Even Longer Select Statement)
)
AS NoOfTweets";
The outcome is correct, but instead of assigning it to "NoOfTweets" it assigns it to "Count(*)". If I remove the "AS NoOfTweets" it stops working. If I remove some brackets it stops working. I'm running low on ideas after a long day! I can post the whole code if needs be but would rather not as it's quite long and I think that bit works.
Thanks in advance, Jack.
Edit: Fixed with:
SELECT COUNT(*) NoOfTweets FROM (
(Long Select Statement)
UNION
(AnotherLong Select Statement)
UNION
(Even Longer Select Statement)
)
AS NoOfTweets";
Thanks guys :)
You aren't putting it in the correct location. The beginning of your query should look like this:
SELECT COUNT(*) AS NoOfTweets
More on Column Alias
SELECT COUNT(*) NoOfTweets FROM
(Long Select Statement)
UNION
(AnotherLong Select Statement)
UNION
(Even Longer Select Statement)
or
SELECT COUNT(*) AS NoOfTweets FROM
(Long Select Statement)
UNION
(AnotherLong Select Statement)
UNION
(Even Longer Select Statement)
You have to use AS exactly after the item you are counting:
SELECT COUNT(*) AS `NoOfTweets`
FROM ( ... )
Also be careful with the " you have near the end. Or maybe it comes from a longer string.
The error is Every derived table must have its own alias which is something I didn't know, so thanks for the education :)
http://sqlfiddle.com/#!9/d30f4/4
Nice of MySQL to give an explanation - I tried with MS SQL on SQLFiddle and just got Incorrect syntax near ')'. which isn't so helpful!
So, your 'NoOfTweets' is the name given to the results column, and also to the 'derived table' which is required by the SQL engine but could be a different name ... it's not returned in the results. The point of naming a derived table is in case you wish to JOIN to other tables and reference the fields in the joins.