简体   繁体   中英

Get number of products sold by name using group by

I have similar table:

CREATE TABLE ForgeRock
    (`id` int, `name` varchar(100), `price` decimal(10,2),`soldtime` datetime)
;

With similar values (random characters in name field)

INSERT INTO ForgeRock
    (`id`, `name`, `price`,`soldtime`)
VALUES
    (1, 'OpenIDM..', 10,'2015-10-11'),
    (2, 'OpenAM....', 20,'2016-1-9'),
    (3, 'OpenDJ...', 30,'2010-1-1'),
    (2, 'OpenAM...', 20,'2016-12-9'),
    (2, 'OpenAM.....', 20,'2016-11-9'),
    (2, 'OpenDJ...', 20,'2016-10-9')
;

Now I am trying to get the count of each product sold using group by:

SELECT *,Count(*) as sc FROM `ForgeRock` Group by name

But I am getting random result(most products are missing). I think it is due to restriction on group by that all non aggregated columns must be part of group by. What is the alternate solution?

Thanks.

Since you just want product and count, you should only ask for product and count rather than "*"

SELECT name, count(*) AS sc FROM ForgeRock GROUP BY name

If you want more "group" data, such as the average price, add it to the list of items selected:

SELECT name, count(*) AS sc, avg(price) AS ap 
FROM ForgeRock 
GROUP BY name

If you want other non-group data you also need to add it to the GROUP BY clause

SELECT name, DATE(soldtime), count(*) AS sc, avg(price) AS ap 
FROM ForgeRock 
GROUP BY name, DATE(soldtime)

This would give you counts and average prices by day.

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