drfu80954 2013-12-18 17:02
浏览 270
已采纳

如何在SQL查询中将select的结果用作偏移量

I was trying to create a single SQL query to return what I need, instead of creating 2 querys, but I need to use the result of one of the querys as the offset of the other one.

My table has user answers with scores, each user may have multiple answers in that table. And I want to calculate the middle point of the table of ordered scores.

Example:

User answers:

  1. User 1 - 5 points
  2. User 1 - 15 points
  3. User 2 - 8 points
  4. User 3 - 12 points

Ranking Table:

  1. User 1 - 20 points
  2. User 3 - 12 points < Middle point
  3. User 2 - 8 points

Solution:

The first query calculates the middle point:

SELECT CEILING(count(Distinct(id_user)) / 2) as position 
FROM us_user_response 
where id_round=1

Query result:

position : 2

This second query creates the ordered ranking table:

SELECT sum(points) as score 
FROM us_user_response 
where id_round=1 
GROUP BY id_user 
Order by score DESC

Now I want to create one big query that returns the score of the middle user, I just need to use the first query result as offset of the second query:

SELECT sum(points) as score 
      FROM us_user_response 
      where id_round=1
      GROUP BY id_user 
      Order by score DESC LIMIT 1
        OFFSET (SELECT CEILING(count(Distinct(id_user)) / 2) as position 
                FROM us_user_response where id_round=1)

Of course, this doesn't work, is there any way to use a result as offset?


EDIT:

The queries work nice! My question is if there is any way to use the result of a query as the offset of another. So I could accomplish this in one single query.

  • 写回答

1条回答 默认 最新

  • dongshao4207 2013-12-21 03:37
    关注

    Try something like this:

    SET @line_id = 0;
    SET @line_offset = (
        SELECT CEILING(count(Distinct(id_user)) / 2) as position 
        FROM us_user_response 
        WHERE id_round = 1
    );
    
    SELECT sum(points) as score,
        IF((@line_id := @line_id + 1) = @line_offset, 1, 0) AS useit 
    FROM us_user_response 
    WHERE id_round = 1
    GROUP BY id_user 
    HAVING useit = 1
    ORDER BY score;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题