Refer to previously selected column in select gives error 1054 - mysql

In
select sum(orders) as total, count(*) as c, c / total as average
It gives an "Error Code: 1054. Unknown column..."
Is there any way to achieve this backreferencing without the very annoying work of wrapping the select in another select?
I imagine this is a duplicate but I haven't been able to find it, so, here's how I would ask it.

The aliased columns don't exist until the query is completed, so you can't use them in the same query.
Just repeat the expressions in the calculation:
select
sum(orders) as total,
count(*) as c,
count(*) / sum(orders) as average
from
yourtable
Or do the select and then the calculation:
select
s.total, s.c, s.c / s.total as average
from
(select
sum(orders) as total,
count(*) as c
from <yourtable>) s

Use the avg function:
select sum(orders) as total, count(*) as c, avg(orders) as average
Based on the column name, I assume you really want the average and not "1 / average" as expressed in your question.

Related

Count how many times distinct values repeat in another column with sql

so I got a column with hundreds of different first names and another column with 7 different neighborhoods that repeat multiple times.
I want to check what are the most common names for each neighborhood. How would I go about it?
Thanks and I hope I made my question clear enough.
I tried the below, and got this error - SQL Error: Syntax error: Encountered " "COUNT" "Count "" at line 8, column 5. Was expecting: EOF
SELECT
host_name, neighbourhood_group,
COUNT(*) AS Ct
FROM AB_NYC_2019
GROUP BY
host_name,
neighbourhood_group,
Max Count AS
(
SELECT
*,
MAX(Ct) OVER
(
PARTITION BY neighbourhood_group
) AS MaxCt
FROM Counts
)
SELECT
neighbourhood_group,
host_name
FROM MaxCounts
WHERE Ct = MaxCt;
select * from
(select host_name,neighbourhood_group, RANK() OVER (PARTITION BY neighbourhood_group order by c desc) as RN
from(select host_name,neighbourhood_group,count(*) as c
from AB_NYC_2019 group by host_name,neighbourhood_group)m)n where
RN=1;

Simple Percentage Column in SQL

I am relatively new to SQL and looking to pick up a few simple tricks. I have managed to create a query that selects each different type of car permit (chargeType), counts the number issued for each one (num), and adds a column that shows the total number of permits issued (total). The code is below.
SELECT chargeType,
COUNT(chargeType) AS num,
(SELECT COUNT(chargeType)
FROM permit) AS total
FROM permit
GROUP BY chargeType
I now want to add a final column which shows the percentage of each permit type issued. So the number of each permit type divided by the total multiplied by 100, but I am struggling to do it. Can anybody help?
Try something like this
SELECT chargeType,
num,
total,
num / NULLIF(total, 0) * 100 AS Percenatge
FROM (SELECT chargeType,
Count(chargeType) AS num,
(SELECT Count(chargeType)
FROM permit) AS total
FROM permit
GROUP BY chargeType) a
NULLIF is used to avoid divide by zero expection
This will work. The plus of this solution is there is no subquery in SELECT
SELECT *, (num * 100 / total) as percentage
FROM
(
SELECT
chargeType,
COUNT(chargeType) AS num,
total,
(num * 100 / total) as percentage
FROM
(SELECT COUNT(chargeType) as total FROM permit) ttotal
CROSS JOIN
permit
GROUP BY
chargeType
) tsub

how to count total record using Union All in mysql

select count(*) from ((select count(*) from employee )
union ALL (select count(*) from events)) as total
this is my query i am trying to find ttoal record by given two query
this query
`select count(*) from employee`
give 300 record and
select count(*) from events
this give 100 when i try to count total record then it give always 2 record can any one tell me how to count total record by give query
You can just add together the two counts directly, no need for a UNION query:
SELECT (SELECT COUNT(*) FROM employee) + (SELECT COUNT(*) FROM events) AS total
Note that this will work because you used UNION ALL, which retains all the records in each side of the query. If you wanted to use a UNION then it would look like this:
SELECT COUNT(*) AS total
FROM
(
SELECT * FROM employee
UNION ALL
SELECT * FROM events
) t
But this would only work if the two tables have the same number (and ideally types) of columns. I would probably go with the first option in any case.
select
count(*) result.union_total
from (
(select 1 from table1)
union all
(select 1 from table2)
) result
Use this command:
SELECT
COUNT(*) AS total
FROM
(SELECT * FROM db_domains where id=695
UNION ALL
SELECT * FROM db_domains where id=694
) AS A;
Result: total: 2 ( According my sql table )
Be sure that:
1.The used SELECT statements have a same number of columns.
Otherwise you will get this error:
Error Code: 1222. The used SELECT statements have a different number of columns
2.Every derived table must have its own alias.
Otherwise you will get this error :
Error Code: 1248. Every derived table must have its own alias
See the snapshot in MYSQL Workbench. ( I have tested on workbench ):
In The last snapshot: You can see the result is: 1106

MySQL Group by Sum Total

I'm getting an error when trying to group by a sum value.
select sum(price + adjustments) as adjusted_price from items group by adjusted_price
Is this not possible?
Example: I want to grab items that have the same adjusted price. Example ( $1.00 - .50 = .50) --- ( $2.00 - 1.50 = .50), I want to grab items that have .50 grouped together.
Thanks
Maybe you are looking for the grand total adjusted_price? If so you don't need the groupby
select
sum(adjusted_price)
from
(select price+adjustments as adjusted_price from items) tt
Edit:
Sounds like you want to group by the adjusted_price. Try the following which will return the frequency count as well:
select
adjusted_price, count(1)
from
(select price+adjustments as adjusted_price from items) tt
group by adjusted_price
Or the following should get you only the unique adjusted_price values:
select distinct
adjusted_price
from
(select price+adjustments as adjusted_price from items) tt
Is this not possible?
Forget about possibility, moreover that looks wrong and incorrect. Why you are trying to group by the SUM() result BTW? You should rather group by any other column in your table. something like below but can't say for sure unless see your table schema and sample data.
select sum(price) + sum(adjustments) as adjusted_price
from items
group by some_column_name;

MySQL query - using SUM of COUNT

This query:
SELECT COUNT(source) AS count
FROM call_details
GROUP BY source
HAVING count >1
Returns about 1500 (the number I'm looking for) results with only the count field. How could I also return the sum of all count fields? When I try
SELECT COUNT(source) AS count,
SUM(count) as total
FROM call_details
GROUP BY source
HAVING count >1
I get an 'Unknown column 'count' in 'field list' error.
And
SELECT COUNT(source) AS count,
SUM(COUNT(source)) as total
FROM call_details
GROUP BY source
HAVING count >1
gives me an 'Invalid use of group function'
Any ideas? I can do a mysql_num_rows($result) of the first set (to get the info I need) but I really want to do it through MySQL.
SELECT COUNT(count) FROM (SELECT COUNT(source) AS count
FROM call_details
GROUP BY source
HAVING count > 1) as A
You can't get a global total in a row-context. At the time the the COUNT() completes on any particular row, there's nothing to SUM, because the other rows haven't been calculated yet.
You'd have to run the SUM query first to get your individual stats, then sum manually in your script, or re-run the query with a surrounding SUM clause:
SELECT SUM(count) FROM (
SELECT original query here...
)
Try this
select mycount, sum(mycount) as sumcount
from
(SELECT COUNT(source) AS mycount FROM call_details GROUP BY source HAVING mycount >1) counttable
Assuming you are going to fetch all the results in the application anyway, I think the most efficient way would be to just sum it up in the application code.
Just simply remove the 'Group by' clause in the select query that counts
# first, get your counts by source
SELECT COUNT(source) AS count
FROM call_details
GROUP BY source
HAVING count >1
# then, get the overall total
SELECT COUNT(source) AS count
FROM call_details
HAVING count >1