Combine instructions with a subquery in SQLite

吃可爱长大的小学妹 提交于 2019-12-25 09:33:49

问题


I have a SQLite table that looks like this:

   ID_TABLE          POINTS_A_TABLE       POINTS_B_TABLE
  id   number       id_a   points_a      id_b   points_b
--------------     ----------------     ----------------
 smith   1         smith     11         smith      25
 gordon  22        gordon    11         gordon     NULL
 butch   3         butch     11         butch      26
 sparrow 25        sparrow   NULL       sparrow    44
 white   76        white     46         white      NULL

With the following command

SELECT id,
       avg(points_a)
FROM (SELECT id_a AS id, points_a FROM points_a_table
      UNION ALL
      SELECT id_b AS id, points_b FROM points_b_table)
GROUP BY id
ORDER BY avg(points_a) DESC;

i'm able to get the average of points associated with each name (more details here)

 id    avg(points_a)
white     46.0  [(46+0)/2]
sparrow   44.0  [(0+44)/2]
butch     18.5  [(11+26)/2]
smith     18.0  [(11+25)/2]
gordon    11.0  [(11+0)/2]

Now I'd like to match the resulting column id with the corresponding columnnumber in ID_TABLE with ID_TABLE.number LESS THAN 26. The result should be (number|average):

76 46.0 [(46+0)/2]

25    44.0  [(0+44)/2]
3     18.5  [(11+26)/2]
76    18.0  [(11+25)/2]
22    11.0  [(11+0)/2]

How can I do that all in one query, by combining new instructions with the previous ones ?


回答1:


You'll need to do a JOIN and then modify your grouping slightly to keep aggregate function working. Assuming that there is exactly one record in id_table for every corresponding record in points_a or points_b:

SELECT i.number,
       avg(pts.points) AS average_points
FROM (SELECT id_a AS id, points_a AS points FROM points_a_table
      UNION ALL
      SELECT id_b AS id, points_b AS points FROM points_b_table) AS pts
INNER JOIN id_table i ON i.id = pts.id
GROUP BY pts.id, i.number
WHERE i.number < 26 
ORDER BY avg(pts.points) DESC;



回答2:


This looks straightforward, using your original query as a subquery. Does this not give you what you want?

SELECT
    idt.number,
    avg_points
FROM
    id_table AS idt
    INNER JOIN (
        SELECT id,
             avg(points_a) AS avg_points
        FROM (SELECT id_a AS id, points_a FROM points_a_table
            UNION ALL
            SELECT id_b AS id, points_b FROM points_b_table)
        GROUP BY id
        ) as x on x.id=idt.id
WHERE
    idt.number < 26;


来源:https://stackoverflow.com/questions/44788025/combine-instructions-with-a-subquery-in-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!