简体   繁体   中英

SQL count without group by

I have a table that has user_id and purchase_id. I want to filter the table so that only users with more than 2 purchases (ie there are more than 2 rows for that user in the table). I used count and group by, but it does not work in a way I want.

create view myview as 
select user_Id, purchase_id, count(*) as count from mytable group by user_Id;

select user_id, purchase_id from myview where count >2;

But it gives me only users (only one user_id) that has more than 2 purchase and it does not give me all of their purchases. For example if the table looks like this:

user_id  purchase_id
1         1212
1         1312
2         1232
1         1321
3         1545
3         4234

My query gives me this :

1     1212
3     1545

But I want this:

1         1212
1         1312
1         1321
3         1545
3         4234

change your last sql like this

select mt.user_id, mt.purchase_id 
from myview mv 
inner join mytable mt 
on mt.user_id=mv.user_id where mv.count >5;
SELECT * 
FROM MYTABLE
WHERE USER_ID IN (SELECT USER_ID
FROM MYTABLE
GROUP BY USER_ID
HAVING COUNT(*)>=2)

I tested in my netezza,it works. hopefully, it's also working in mysql

Try GROUP BY with HAVING comment.

SELECT user_Id, purchase_id 
FROM mytable
GROUP BY user_Id 
HAVING count( * ) >5

As far as I can tell you want to list the user id's and purchase id's of all users that have over 5 purchases.

In order to do this you could do a join on two queries. For example:

SELECT tblLeft.user_id, 
       tblLeft.purchase_id 
FROM   myview tblLeft 
       JOIN (SELECT user_id, 
                    Count(*) AS purchases 
             FROM   myview 
             GROUP  BY user_id 
             HAVING purchases > 1) tblRight 
         ON tblLeft.user_id = tblRight.user_id 

The tblRight is essentially a table containing the user_id's of all users with over 5 purchases. We then do a select (tblLeft) and join it on the tbl right, ensuring only customers with over 5 purchases remain.

SELECT
     *
FROM
     mytable mt, 
     (SELECT user_id, count(*) AS purchase_count FROM mytable GROUP BY user_id) ct
WHERE
     mt.user_id = ct.user_id AND ct.purchase_count > 5;

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