How to use the result of an SQL statement in a math expression? - sql

I have two SELECT statements that return a number each, and I'd like to divide one by the other.
Something like the following, if it would work:
SELECT
SELECT
SUM(SIZE)
FROM
GLOBAL_STATS_V_M
WHERE
ID IN ("DuplicatedRule", "OldRule", "RevRule", "TmpRule")
/
SELECT
SUM(SIZE)
FROM
GLOBAL_STATS_V_M
WHERE
ID IN ("Total")
That gets a 'Query Error: near "SELECT": syntax error Unable to execute statement'.
Adding parenthesis does not help.
How to do this?
I'm using Sqliteman

You need to add parenthesis:
SELECT
(SELECT
SUM(SIZE)
FROM
GLOBAL_STATS_V_M
WHERE
ID IN ("DuplicatedRule", "OldRule", "RevRule", "TmpRule")
)
/
(SELECT
SUM(SIZE)
FROM
GLOBAL_STATS_V_M
WHERE
ID IN ("Total")
)

Two problems here.
You need parenthesis around both sub select statements.
You need to finish the outer statement with FROM DUAL.
select
(select ....) / (select ....) as total
from
dual
I actually would prefer to write the query differently for cleanliness.
select subtotal.total / alltotal.total
from (select sum(size) as total .... where id in ("Duplic....) ) subtotal,
(select sum(size) as total .... where id in ("total") ) alltotal

Related

How to use to functions - MAX(smthng) and after COUNT(MAX(smthng)

I don't understand why I can't use this in my code :
SELECT MAX(SMTHNG), COUNT(MAX(SMTHNG))
FROM SomeTable;
Searched for an answer but didn't find it in documentation about these aggregate functions.
Also I get an SQL-compiler error "Invalid column name "SMTHNG"".
You want to know what the maximum SMTHNG in the table is with:
SELECT MAX(SMTHNG) FROM SomeTable;
This is an aggregation without GROUP BY and hence results in one single row containing the maximum SMTHNG.
Now you also want to know how often this SMTHNG occurs and you add COUNT(MAX(SMTHNG)). This, however, does not work, because you can not aggregate an aggregate directly.
This doesn't work either:
SELECT ANY_VALUE(max_smthng), COUNT(*)
FROM (SELECT MAX(smthng) AS max_smthng FROM sometable) t;
because the sub query only contains one row, so it's too late to count.
So, either use a sub query and select from the table again:
SELECT ANY_VALUE(smthng), COUNT(*)
FROM sometable
WHERE smthng = (SELECT MAX(smthng) FROM sometable);
Or count per SMTHNG before looking for the maximum. Here is how to get the counts:
SELECT smthng, COUNT(*)
FROM sometable
GROUP BY smthng;
And the easiest way to get the maximum from this result is:
SELECT TOP(1) smthng, COUNT(*)
FROM sometable
GROUP BY smthng
ORDER BY COUNT(*) DESC;
First of all, please read my comment.
Depending on what you're trying to achieve, the statement have to be changed.
If you want to count the highest values in SMTHNG field, you may try this:
SELECT T1.SMTHNG, COUNT(T1.SMTHNG)
FROM SomeTable T1 INNER JOIN
(
SELECT MAX(SMTHNG) AS A
FROM SomeTable
) T2 ON T1.SMTHNG = T2.A
GROUP BY T1.SMTHNG;
use cte like below or subquery
with cte as
(
select count(*) as cnt ,col from table_name
group by col
) select max(cnt) from cte
you can not use double aggregate function at a time on same column

How to use count & distinct together for all columns

I am getting error while executing the following query.
SELECT COUNT(distinct *) AS "total unique records" FROM table
Please help me to resolve this issue
Because * is not allowed there. If you want to do this, use a subquery:
select count(*)
from (select distinct t.*
from t
) t;
You probably want :
select count(*)
from (select distinct t.*
from table t
) t;
Use this code too count row
SELECT COUNT(*) AS TotalRecords FROM table
AND use that too count row and return order columns
SELECT COUNT(*) OVER() AS TotalRecords,* FROM table

Oracle sql missing right parenthesis

I'm trying to limit the number of rows that would be displayed when I run my query.
When I run the code below in SQL developer, it returns missing right parenthesis error..
select * from
(select row_number() over (order by rescode) rnum, a.* from
(
SELECT *
FROM trans z
LEFT JOIN emails a
ON z.email1_hist_id=a.email_id
or z.email2_hist_id=a.email_id
) a
) where rnum between 1 and 50;
I tried running the inside query:
SELECT *
FROM trans z
LEFT JOIN emails a
ON z.email1_hist_id=a.email_id
or z.email2_hist_id=a.email_id
and it works fine. On the other hand I tried removing the OR portion of my query and included the limit rows query and it returns the number of rows I specified.
What exactly is wrong in my code?
This should work - you don't need two levels of subquery
select *
from
( SELECT *, row_number() over (order by rescode) rnum
FROM trans z
LEFT JOIN emails a
ON (z.email1_hist_id=a.email_id or z.email2_hist_id=a.email_id)
) x
where rnum between 1 and 50;
Also, make sure there are no duplicate column names between trans and emails - this will trip the query because * from the inner query cannot return duplicate names.
My best guess is that it doesn't like your giving the sub-selection an alias, so it's throwing the syntax error at the "a" in ") a )".
I don't recall about Oracle, but I know that MySQL actually requires sub-selections to have an alias. I'd try adding one to your outer sub-select (before the where rnum...).

SELECT *, COUNT(*) in SQLite

If i perform a standard query in SQLite:
SELECT * FROM my_table
I get all records in my table as expected. If i perform following query:
SELECT *, 1 FROM my_table
I get all records as expected with rightmost column holding '1' in all records. But if i perform the query:
SELECT *, COUNT(*) FROM my_table
I get only ONE row (with rightmost column is a correct count).
Why is such results? I'm not very good in SQL, maybe such behavior is expected? It seems very strange and unlogical to me :(.
SELECT *, COUNT(*) FROM my_table is not what you want, and it's not really valid SQL, you have to group by all the columns that's not an aggregate.
You'd want something like
SELECT somecolumn,someothercolumn, COUNT(*)
FROM my_table
GROUP BY somecolumn,someothercolumn
If you want to count the number of records in your table, simply run:
SELECT COUNT(*) FROM your_table;
count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by
If what you want is the total number of records in the table appended to each row you can do something like
SELECT *
FROM my_table
CROSS JOIN (SELECT COUNT(*) AS COUNT_OF_RECS_IN_MY_TABLE
FROM MY_TABLE)

adding count( ) column on each row

I'm not sure if this is even a good question or not.
I have a complex query with lot's of unions that searches multiple tables for a certain keyword (user input). All tables in which there is searched are related to the table book.
There is paging on the resultset using LIMIT, so there's always a maximum of 10 results that get withdrawn.
I want an extra column in the resultset displaying the total amount of results found however. I do not want to do this using a separate query. Is it possible to add a count() column to the resultset that counts every result found?
the output would look like this:
ID Title Author Count(...)
1 book_1 auth_1 23
2 book_2 auth_2 23
4 book_4 auth_.. 23
...
Thanks!
This won't add the count to each row, but one way to get the total count without running a second query is to run your first query using the SQL_CALC_FOUND_ROWS option and then select FOUND_ROWS(). This is sometimes useful if you want to know how many total results there are so you can calculate the page count.
Example:
select SQL_CALC_FOUND_ROWS ID, Title, Author
from yourtable
limit 0, 10;
SELECT FOUND_ROWS();
From the manual:
http://dev.mysql.com/doc/refman/5.1/en/information-functions.html#function_found-rows
The usual way of counting in a query is to group on the fields that are returned:
select ID, Title, Author, count(*) as Cnt
from ...
group by ID, Title, Author
order by Title
limit 1, 10
The Cnt column will contain the number of records in each group, i.e. for each title.
Regarding second query:
select tbl.id, tbl.title, tbl.author, x.cnt
from tbl
cross join (select count(*) as cnt from tbl) as x
If you will not join to other table(s):
select tbl.id, tbl.title, tbl.author, x.cnt
from tbl, (select count(*) as cnt from tbl) as x
My Solution:
SELECT COUNT(1) over(partition BY text) totalRecordNumber
FROM (SELECT 'a' text, id_consult_req
FROM consult_req cr);
If your problem is simply the speed/cost of doing a second (complex) query I would suggest you simply select the resultset into a hash-table and then count the rows from there while returning, or even more efficiently use the rowcount of the previous resultset, then you do not even have to recount
This will add the total count on each row:
select count(*) over (order by (select 1)) as Cnt,*
from yourtable
Here is your answare:
SELECT *, #cnt count_rows FROM (
SELECT *, (#cnt := #cnt + 1) row_number FROM your_table
CROSS JOIN (SELECT #cnt := 0 AS variable) t
) t;
You simply cannot do this, you'll have to use a second query.