6

I've read this article: http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/ and search for other questions

I have a table that is something like:

| table.id    | USER.id
----------------------------------------------
| 1           | 101
| 2           | 101
| 3           | 101
| 4           | 101 
| 5           | 101
| 6           | 101
| 7           | 101 
| 8           | 101
| 9           | 101 
| 10          | 101
| 11          | 102
| 12          | 102 
| 13          | 102
| 14          | 102
| 15          | 103 
| 16          | 103
| 17          | 103
| 18          | 103
| 19          | 103
| 20          | 103
| 21          | 103
| 22          | 103 
| 23          | 103
| 24          | 104
| 25          | 104 
| 26          | 104
| 27          | 104
| 28          | 104
| 29          | 104
| 30          | 105
| 31          | 105
| 32          | 105 
| 33          | 106
| 34          | 106

I'm trying to get the count of table.id grouped by user.id, and if the count of user.id is more than 7, only display the result as 7 (aka limiting the count results to 7).

In this example, the result should be:

| USER.id         | count of table.ID
----------------------------------------
| 101             | 7
| 102             | 4
| 103             | 7
| 104             | 6
| 105             | 3
| 106             | 2

I've tried:

SELECT USERid, COUNT(table.id)
FROM table
WHERE table.id IN (select top 7 table.id from table)
GROUP BY USERid

and

SELECT USERid, COUNT(table.id)
FROM table
WHERE (
    SELECT COUNT(table.ID) FROM table as t
    WHERE t.id = t.id AND t.USERid <= table.USERid
    ) <= 7
GROUP BY USERid

3 Answers 3

8

You can simplify your query, and use LEAST function

SELECT USERid, LEAST(7, COUNT(*))
FROM table
GROUP BY USERid

from the question in your comment

SELECT SUM(countByUser) 
FROM
 (SELECT LEAST(7, COUNT(*)) as countByUser
  FROM table
  GROUP BY USERid) c

SqlFiddle

2
  • Works great! And very simple. How would I get the SUM of that COUNT column? I tried SELECT userid, SUM(SELECT LEAST(7, COUNT(*)) FROM table GROUP BY USERid) FROM table, though this resulted in error
    – Ken
    Oct 3, 2013 at 20:48
  • Yes the sum of that count column. In the original example, the sum of the count column with the limit of 7 results max would be = 29
    – Ken
    Oct 3, 2013 at 20:50
1
SELECT userid,
CASE
  WHEN COUNT(*) > 7 THEN 7
  ELSE COUNT(*)
END AS Qty
FROM tbl
GROUP BY userid
0
SELECT USERid, case when COUNT(table.id) > 7 
                    then 7 
                    else COUNT(table.id) 
               end
FROM table
GROUP BY USERid

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.