mysql : display multiple results with heading - mysql

I'm a complete newb so forgive me.
I'm trying to get the results to display 2 or more different headings.
SELECT sum(fare) AS totalfare, count(*) AS fare10
where fare>10
FROM tbl
I'm trying to get the WHERE statement apply to only count, not the sum, and have the result display as "totalfare" "fare10"
SELECT sum(fare) AS totalfare
FROM tbl
union
SELECT count(*) AS watever
FROM tbl
where fare > 10
I've tried this way, but the result grid would spit out the answers under 1 heading as totalfare. Is it possible to display it as totalfare | whatever?

Finally you explained your question. You can do UNION only when you have tables (result sets) with the same fields. This is what you need. The above query selects directly from the derived table created by the two sub-queries.
SELECT
*
FROM
(SELECT
SUM(fare) AS totalfare
FROM
tbl) a,
(SELECT
COUNT(*) AS watever
FROM
tbl
WHERE
fare > 10) b
You will get results as one row
[ totalfare | watever ]
number number

You want conditional aggregation:
SELECT sum(fare) AS totalfare,
sum(case when fare > 10 then 1 else 0 end) as fare10
FROM tbl;
In MySQL you can also shorten this to:
SELECT sum(fare) AS totalfare,
sum(fare > 10) as fare10
FROM tbl;

Related

Sql - Query to get total number of records in table

I have table like this
enter image description here
I need to get the data only whose age > 10, along with that i need to get the total number of records present in the table. ie. in this example it is 4 records. what i need is in single query i need to get the total number of records present in table and columns which i query.
Query will be somewhat like
SELECT ID, NAME, count(TOTAL NUMBER OF RECORDS IN TABLE) as Count from MYTABLE WHERE AGE > 10
Any idea about this ?
You can use a subquery in the FROM clause:
SELECT ID, NAME, c.cnt as Count
FROM MYTABLE CROSS JOIN
(SELECT COUNT(*) as cnt FROM MYTABLE) c
WHERE AGE > 10 ;
Both databases support window functions, but they are not really helpful here, because the count is not filtered in the same way as the outer query. If you do want the filter for both, then in the most recent versions you can do:
SELECT ID, NAME, COUNT(*) OVER () as cnt
FROM MYTABLE
WHERE AGE > 10 ;
You can try below - using scalar subquery
SELECT ID, NAME, age,(select count(*) from mytable WHERE AGE > 10) as Count
from MYTABLE
WHERE AGE > 10

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

One MySQL query to get AVG by different Groupings?

Wondering is there is a way to write the following in ONE MySQL query.
I have a table:
cust_ID | rpt_name | req_secs
In the query I'd like to get:
the AVG req_secs when grouped by cust_ID
the AVG req_secs when grouped by rpt_name
the total req_secs AVG
I know I can do separate grouping queries on the same table then UNION the results into one. But I was hoping there was some way to do it in one query.
Thanks.
Well, the following would does two out of three:
select n,
(case when n = 1 then cast(cust_id as varchar(255)) else rpt_name end) as grouping,
avg(req_secs)
from t cross join
(select 1 as n union all select 2
) n
group by n, (case when n = 1 then cust_id else rpt_name end);
This essentially "doubles" the data and then does the aggregation for each group. This assumes that cust_id and rpt_name are of compatible types. (The query could be tweaked if this is not the case.)
Actually, you can get the overall average by using rollup:
select n,
(case when n = 1 then cust_id else rpt_name end) as grouping,
avg(req_secs)
from t cross join
(select 1 as n union all select 2
) n
group by n, (case when n = 1 then cast(cust_id as varchar(255)) else rpt_name end) with rollup
This works for average because the average is the same on the "doubled" data as for the original data. It wouldn't work for sum() or count().
No there is not. You can group by a combination of cust_ID and rpt_name at the same time (i.e. two levels of grouping) but you are not going to be able to do separate top-level groupings and then a non-grouped aggregation at the same time.
Because of the way GROUP BY works, the SQL to do this is a little tricky. One way to get the result is to get three copies of the rows, and group each set of rows separately.
SELECT g.gkey
, IF(g.grp='cust_id',t.cust_ID,IF(g.grp='rpt_name',t.rpt_name,'')) AS gval
, AVG(t.req_secs) AS avg_req_secs
FROM (SELECT 'cust_id' AS gkey UNION ALL SELECT 'rpt_name' UNION ALL SELECT 'total') g
CROSS
JOIN mytable t
GROUP
BY g.gkey
, IF(g.grp='cust_id',t.cust_ID,IF(g.grp='rpt_name',t.rpt_name,''))
The inline view aliased as "g" doesn't have to use UNION ALL operators, you just need a rowset that returns exactly 3 rows with distinct values. I just used the UNION ALL as a convenient way to return three literal values as a rowset, so I could join that to the original table.

MySQL select occurence by count

I have a table with two columns like this:
source_cid inchikey
---------- --------
1 qqmn
2 qqmn
3 ccmm
Now I want to select source_cids which have same inchikeys
Here is my query:
SELECT source_cid, count(*) as c
FROM inchikey
GROUP BY inchikey HAVING count(*)>1
This code runs forever. How can I modify it?
First off, as Anigel has stated we need to see your create statements and you should be using indexes.
Secondly, your query does not display all the rows that should be displayed.
See: http://www.sqlfiddle.com/#!2/a810d/7
SELECT source_cid, count(*) as c
FROM inchikey
GROUP BY inchikey HAVING count(*)>1;
Unfortunately only row with source_cids 1 is outputted.
select * from inchikey i,
(
SELECT i2.inchikey, count(i2.source_cid) as c
FROM inchikey i2
GROUP BY i2.inchikey HAVING count(i2.source_cid)>1
) as cd
where cd.inchikey = i.inchikey;
With this, rows with 1 and 2 are outputted.
Try creating a repeating index on (source_cid, inchikey) on table inchikey, then try running the query:
SELECT inchikey, group_concat(distinct source_cid) source_cids, count(*) as c
FROM inchikey
GROUP BY inchikey HAVING count(distinct source_cid)>1
(Your existing query will only show one source_cid for each repeating inchikey.)

Average on a count() in same query

I'm currently working on an assignment which requires me to find the average on the number of resources for each module. The current table looks like this:
ResourceID ModulID
1 1
2 7
3 2
4 4
5 1
6 1
So basically, I'm trying to figure out how to get the average number of resources. The only
relevant test data here is for module 1, which has 3 different resources connected to it. But I need to display all of the results.
This is my code:
select avg(a.ress) GjSnitt, modulID
from
(select count(ressursID) as ress
from ressursertiloppgave
group by modulID) as a, ressursertiloppgave r
group by modulID;
Obviously it isn't working, but I'm currently at loss on what to change at this point. I would really appreciate any input you guys have.
This is the query you are executing, written in a slightly less obtuse syntax.
SELECT
avg(a.ress) as GjSnitt
, modulID
FROM
(SELECT COUNT(ressursID) as ress
FROM ressursertiloppgave
GROUP BY modulID) as a
CROSS JOIN ressursertiloppgave r <--- Cross join are very very rare!
GROUP BY modulID;
You are cross joining the table, making (6x6=) 36 rows in total and condensing this down to 4, but because the total count is 36, the outcome is wrong.
This is why you should never use implicit joins.
Rewrite the query to:
SELECT AVG(a.rcount) FROM
(select count(*) as rcount
FROM ressursertiloppgave r
GROUP BY r.ModulID) a
If you want the individual rowcount and the average at the bottom do:
SELECT r1.ModulID, count(*) as rcount
FROM ressursertiloppgave r1
GROUP BY r1.ModulID
UNION ALL
SELECT 'avg = ', AVG(a.rcount) FROM
(select count(*) as rcount
FROM ressursertiloppgave r2
GROUP BY r2.ModulID) a
I got the solution
SELECT AVG(counter)
FROM
(
SELECT COUNT(column to count) AS counter FROM table
) AS counter
Note that the nickname {counter} was added in SELECT COUNT and at the end of the inner SELECT