简体   繁体   中英

SQLite select all records and count

I have the following table:

CREATE TABLE sometable (my_id INTEGER PRIMARY KEY AUTOINCREMENT, name STRING, number STRING);

Running this query:

SELECT * FROM sometable;

Produces the following output:

1|someone|111
2|someone|222
3|monster|333

Along with these three fields I would also like to include a count representing the amount of times the same name exists in the table.

I've obviously tried:

SELECT my_id, name, count(name) FROM sometable GROUP BY name;

though that will not give me an individual result row for every record.

Ideally I would have the following output:

1|someone|111|2
2|someone|222|2
3|monster|333|1

Where the 4th column represents the amount of time this number exists.

Thanks for any help.

You can do this with a correlated subquery in the select clause:

Select st.*,
       (SELECT count(*) from sometable st2 where st.name = st2.name) as NameCount
from sometable st;

You can also write this as a join to an aggregated subquery:

select st.*, stn.NameCount
from sometable st join
     (select name, count(*) as NameCount
      from sometable
      group by name
    ) stn
    on st.name = stn.name;

EDIT:

As for performance, the best way to find out is to try both and time them. The correlated subquery will work best when there is an index on sometable(name) . Although aggregation is reputed to be slow in MySQL, sometimes this type of query gets surprisingly good results. The best answer is to test.

Select *, (SELECT count(my_id) from sometable) as total from sometable 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM