Mysql查询计数器x / y

时间:2016-07-11 14:21:18

标签: mysql

可以创建一个返回x / y记录数的查询吗?

EG。 我有这样的表

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

我将返回看起来像这样的内容:

事件

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**

任何建议都表示赞赏!

4 个答案:

答案 0 :(得分:0)

试试这个

SET @id_event  := 0;
SELECT CONCAT('id_user ', id_user ,'->','**', (@id_event  := @id_event  + 1)  ,'/', id_user ,** ) from table

答案 1 :(得分:0)

这可能与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;

答案 2 :(得分:0)

假设你想要这样的输出:

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

您可以通过以下查询完成此类结果:

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

更多

SQL FIDDLE DEMO 2

这个特殊的小提琴只返回所需的输出列,而第一小提琴包含一个额外的列

答案 3 :(得分:0)

我玩了一点,这将是我的解决方案:

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
如果@n和id_user匹配,如果不是@n成为id_user并且@c再次为1,那么只有两个条件用于计算@c up。连接用于在同一查询中初始化var。

对于那个问题,我找到了我4天前提出的问题的答案。