I'm looking to store the results of a query that returns a list of all the unique values in a particular column, and how many times they are repeated:
SELECT col_name, COUNT(*) AS 'total' FROM dataTable GROUP BY col_name;
This returns something like:
col_name
recordA
recordB
recordC
recordD
recordE...
total
39
91817
982027
211872
256...
It's working great and exactly what I need. But I need to store the results into another table (eg. countTable) so I don't have to do the query every time, can index it... etc.
Let's say countTable has the exact same structure as the results here. Two columns: name and count of the same types as the original result.
This is going to probably raise some laughs, but currently I feel like this is close:
INSERT INTO countTable (name, count) SELECT col_name, total FROM
(SELECT col_name, COUNT(*) AS 'total' FROM dataTable GROUP BY col_name);
But I get an error: ERROR 1248 (42000): Every derived table must have its own alias
I have no idea how to wrap this query right, or if I'm supposed to use another AS somewhere?
Any help greatly appreciated!!
Thanks
You can do a SELECT right after the INSERT statement. As long as what you are selecting matches the values you want to insert (in this case name and count). You can test what will be inserted into your countTable by just running the select statement by itself.
INSERT INTO countTable (name, count)
SELECT col_name, COUNT(*) AS 'total'
FROM dataTable
GROUP BY col_name;
AH! Turns out I was very close in my original query:
INSERT INTO countTable (name, count) SELECT col_name, total FROM
(SELECT col_name, COUNT(*) AS 'total' FROM dataTable GROUP BY col_name);
I DID need to add an extra AS at the very end. Every derived table MUST indeed have its own alias :)
INSERT INTO countTable (name, count) SELECT col_name, total FROM
(SELECT col_name, COUNT(*) AS 'total' FROM dataTable GROUP BY col_name) AS count;
But it would seem I'm wrapping it unnecessarily as evidenced by spaceman's answer.
Related
I'm trying to insert a new row in a table with count numbers from select statements from different tables. When I run the following, it creates the row but inserts 0 for the two fields with the select statements (instead of values 1047 and 8 that I get when I run the select statements individually) . I tried putting the select statements inside the insert statement as well but that was throwing errors. Any help on where I'm going wrong? Thanks in advance.
select count(*) from research.Neuro_Recruited_MG as letters_sent;
select count(*) from research.neuro_subject_log s where s.enrolled like 'PS' as pending_screening;
insert into neuro_stats (id, letters_sent, pending_screening)
values (3, 'letters_sent','pending_screening’)
You're running three separate statements. The first two (the SELECTs) execute, but starting the next one discards the one before it.
Try something like this instead:
insert into neuro_stats
(id, letters_sent, pending_screening)
values
(3,
(select count(*) from research.Neuro_Recruited_MG),
(select count(*) from research.neuro_subject_log s where s.enrolled like 'PS'));
try, assuming id is auto_increment.
insert neuro_stats(letters_sent, pending_screening)
select sum(count_letters_sent), sum(count_pending_Screening)
from (
select count(*) as count_letters_sent, 0 as count_pending_screening)
from research.neuro_recruited_MG
UNION
select 0 as count_letters_sent, count(*) as count_pending_screening
from reserach.neuro_subject_log as s
where s.enrolled like '%PS%'
) as xcount;
may be your like 'PS' needs the wildcard character % before and/or after your 'PS' in fact of a search like "beginning", "containing" or "ending" with 'PS'
All I need to do is to count all records that match this query... that is the only info I need.. is the count of the records... what is the most efficient way to do that?
SELECT id, country, city
FROM sales
WHERE country='Germany'
AND city='Munich'
AND closed<>0
I mean, I assume this is correct but is there a more efficient way to do this? I will be running this counting query often...
SELECT COUNT(*)
FROM sales
WHERE country='Germany'
AND city='Munich'
AND closed<>0
Should I use * or something more specific?
If you need to count the Null value also for your record count then use count(*) or if ignore the Null value to be counted then use count().
DECLARE #AA AS TABLE (ID INT, NAME VARCHAR(10))
INSERT INTO #AA VALUES(1,NULL)
INSERT INTO #AA VALUES(2,'A')
INSERT INTO #AA VALUES(3,'B')
INSERT INTO #AA VALUES(4,'C')
SELECT * FROM #AA
SELECT COUNT(*) FROM #AA
SELECT COUNT(NAME) FROM #AA
As you execute the above query you can find that there will be four records in #AA table but if you use COUNT(*) if will result 4 and if you use COUNT(NAME) it will result 3 this example is for SQL Server, but the mysql will do same.
Please refer the following link.
MySQL: Fastest way to count number of rows
Hope this helps you.
I have this mssql query:
with RESULT as(select TITLE, URL, ROW_NUMBER() over (order by URL) as SeqValue from WEBSITE
select * from RESULT where SeqValue>=20 and SeqValue<=40
I'd like to know how many record this query would return if the where statement was not there.
I try with select count(*) from RESULT and try with ##ROWCOUNT and many others way but did not work.
I need TITLE and URL from select, and in the end i need total record for the select.
For example in mysql query i have prepareStatement using SQL_CALC_FOUND_ROWS:
select SQL_CALC_FOUND_ROWS TITLE, URL from WEBSITE limit ?, ?
and after this select i have:
select FOUND_ROWS()
In this example returned value is total record for the mysql query.
Total record is same with LIMIT and without LIMIT directive.
I convert database from mysql to mssql and i have problem with this.
Please help me...
I had the same concern when trying to move from MySQL to SQL SERVER
the solution is to inject this in your query:
COUNT (*) OVER () AS ROW_COUNT
ROWCOUNT appear in all rows in the result then it only remains for you to retrieve ROW_COUNT from the first row result (if exists) and not forget to reset the result pointer et Voila;-).
for example:
select COUNT (*) OVER () AS ROW_COUNT, URL from WEBSITE limit ?, ?
I hope it will help
"RESULT" is going to include every record in WEBSITE, right? So just "select count(*) from WEBSITE".
I would expect
with result as(...what you have...)
select count(*) from result;
To work too, with some unnecessary work. What does that not do that you want?
try:
declare #row_count int
select #row_count = count(*), URL from WEBSITE limit ?, ?
select #row_count
I know it is too late, but can be helpful with pagination and limits.
WITH paging AS (SELECT ROW_NUMBER() OVER(ORDER BY {$sortField} {$sortOrder}) as rowId, count(1) over() as ROW_COUNT, key FROM {$table})
SELECT * FROM {$table} result INNER JOIN paging ON result.key = paging.key WHERE rowId BETWEEN {$start} and {$end}
It has the property for sorting field, sort order and key is used to join the original table. The start and end are the values of your pagination.
Now you have total number of records on ROW_COUNT field with required fields. It also starts from 1 and not from 0.
I have a simple table with two columns. The first field represents an id, the second one a name (string value). No field is unique. So, e.g., there are many records like:
What I need is a simple SQL statement which shows me the whole table in the following format and inserts the content into a new table.
Any help?
You have to use group by:
insert into tab2 (name,cnt)
select name, count(1) as cnt
from tab
group by name
Here is more informations about aggregate functions.
SQL Fiddle DEMO
Just use COUNT function to count from_id. And if you want to count in group, use GROUP BY clause for that. Like this one.
SELECT `name`, COUNT(from_id) AS `COUNT`
FROM myTable
GROUP BY `name`;
This will return your desired result.
Now you want to insert it into new table then you can do like this:
INSERT INTO newTable (`name`, `count`)
SELECT `name`, COUNT(from_id) AS `COUNT`
FROM myTable
GROUP BY `name`;
I have a query with many wheres and orders criterias. One of the fields of the select is 'price' (element price) but I would like to have also (in every row) the maximun price of all the selected elements.
I tried to include MAX aggregate function on select hoping that this will return desired value, but insetead of that, price and MAX(price) returns the same. Searching into MySql doc I found the reason:
If you use a group function in a
statement containing no GROUP BY
clause, it is equivalent to grouping
on all rows.
Is there a way to solve this problem?
Thanks in advance!
There's a similar question (but not resolving this): find max value without aggregate operator in mysql
You can do this:
SELECT
id,
price,
(SELECT MAX(price) FROM your_table) AS max_price
FROM your_table
I'm not sure why you'd want to return that value on every row though... I'd probably do this in two separate queries, or else use a UNION ALL:
SELECT id, price FROM your_table
UNION ALL
SELECT NULL, MAX(price) FROM your_table
Maybe you could use a stored procedure like so:
CREATE PROCEDURE QueryWithMax ([parameter list if necessary])
BEGIN
-- Obtain the maximum price
DECLARE x INT UNSIGNED; -- change datatype if appropriate
SET x = SELECT
MAX(price)
FROM
...
WHERE
...
;
-- Now do your query
SELECT
price,
[other columns],
x AS MaxPrice
FROM
...
WHERE
...
GROUP BY
...
;
END
I haven't tried this, but if you had a subquery that extracts the maximum price (so you get one row), and then do a cross join (cartesian product) with it. You should get something like what you want. I can't vouch for how fast this would be.