1

It's possible to create a query that return the x/y number of records?

Eg. I have table like this

ID | id_user | id_event  
23 | 3       | 1 
24 | 3       | 1 
25 | 3       | 1 
26 | 4       | 2
27 | 4       | 2

I will return something that looks like this:

Event

id_user 3 -> **1/3**
id_user 3 -> **2/3**
id_user 3 -> **3/3**
id_user 4 -> **1/2**
id_user 4 -> **2/2**

Any suggestion is appreciated!

too
  • 21
  • 2

4 Answers4

0

Try this

SET @id_event  := 0;
SELECT CONCAT('id_user ', id_user ,'->','**', (@id_event  := @id_event  + 1)  ,'/', id_user ,** ) from table
Wasiq Muhammad
  • 3,080
  • 3
  • 16
  • 29
0

This is probably a duplicate to this question.

SELECT CONCAT('id_user ',id_user,' -> **',rank,'/',group_total,'**') FROM (
    SELECT id, 
        group_total,
        CASE id_user 
            WHEN @id_user THEN
                CASE id_event 
                    WHEN @id_event THEN @rowno := @rowno + 1 
                    ELSE @rowno := 1
                END
            ELSE @rowno :=1
        END AS rank,
        @id_user := id_user AS id_user,
        @id_event := id_event AS id_event
    FROM event_table
    JOIN (SELECT id_user, id_event, COUNT(*) group_total FROM event_table GROUP BY id_user, id_event) t USING (id_user, id_event)
    JOIN (SELECT @rowno := 0, @id_user := 0, @id_event := 0) r
    ORDER BY id_user, id_event
) c;
Community
  • 1
  • 1
0

Assuming you want output like this:

id_user < id_user > ** serial number of event related to this user / total events related to this user **

You can accomplish such result by the following query:

SELECT 
CONCAT('id_user ',UE.id_user,' -> **',IF(@userID = UE.id_user, @eventNumber := @eventNumber + 1, @eventNumber := 1),'/',t.totalEvents,'**') AS output,
@userID := UE.id_user
FROM (SELECT @userID := -1, @eventNumber := 1) var,user_events UE 
INNER JOIN 
(
    SELECT 
        id_user,
        COUNT(id_event) totalEvents
    FROM user_events
    GROUP BY id_user
) AS t
ON UE.id_user = t.id_user
ORDER BY UE.id_user;

SQL FIDDLE DEMO

More:

SQL FIDDLE DEMO 2

This particular fiddle returns only the desired output column whereas the first fiddle contains one extra column

1000111
  • 13,169
  • 2
  • 28
  • 37
0

I played a little bit and that would be my solution:

SELECT id, id_user, id_event, if(@n = a.id_event, @c:=@c+1, if(@n:=a.id_event, @c:=1, @c:=1)) as count, (SELECT count(*) from TABLE b WHERE a.id_user = b.id_user) as total, from TABLE a join (SELECT @n:= "", @c:=1) c

It just have two if conditions for counting a @c up if @n and id_user matches if not @n become id_user and @c is 1 again. The join is for initialize the var in the same query.

Thx to that question, i found the answer to a questions that i asked 4 days ago.

thentt
  • 16
  • 4