如何组合以下两个返回用户最近x和最近y的查询?

时间:2018-02-15 01:36:44

标签: postgresql

此查询返回最近使用的x:

SELECT
DISTINCT ON (usersq1.id) usersq1.id AS user_id,
usersq1.name,
x_id AS last_x_used, started_at AS x_date
FROM usersq1
LEFT OUTER JOIN tripsq1
ON usersq1.id = user_id
ORDER BY usersq1.id;

它返回一个与此类似的表:

 user_id |        name         | last_x_used    | x_date
---------+---------------------+----------------+------------
    1001 | Makeda Mosser       |            113 | 2017-06-07
    1002 | Libbie Luby         |            115 | 2017-06-09
    1003 | Linn Loughran       |            103 | 2017-06-03
    1004 | Natacha Ned         |            104 | 2017-06-04
    1005 | Lorrine Lunt        |            105 | 2017-06-05
    1006 | Tami Tineo          |            106 | 2017-10-06
    1007 | Delisa Deen         |            107 | 2017-10-07
    1008 | Mimi Miltenberger   |            108 | 2017-10-08
    1009 | Seth Sneller        |            109 | 2017-10-09
    1010 | Rickie Rossi        |            110 | 2017-10-10
    1011 | Jenise Jeanbaptiste |            101 | 2017-06-01
    1012 | Genia Glatz         |            101 | 2017-06-02
    1013 | Onita Oddo          |            101 | 2017-06-03
    1014 | Dario Dreyer        |            102 | 2017-06-04
    1015 | Toby Trent          |                |

此查询返回最近使用的y:

SELECT
DISTINCT ON (usersq1.id) usersq1.id AS user_id,
usersq1.name,
tripsq1.id AS trip_id, y_id  AS last_y_used, started_at AS y_date
FROM usersq1
LEFT OUTER JOIN tripsq1
ON usersq1.id = user_id
WHERE coupon_id IS NOT NULL
ORDER BY usersq1.id, y_id DESC;

它返回一个与此类似的表:

 user_id |        name         | last_Y      | Y_date
---------+---------------------+-------------+-------------
    1001 | Makeda Mosser       |           4 | 2017-06-02
    1002 | Libbie Luby         |           7 | 2017-06-02
    1011 | Jenise Jeanbaptiste |           5 | 2017-06-30
    1012 | Genia Glatz         |           6 | 2017-07-02

我想写一个查询,结果显示user_id,user_name,last_x_used,x_date,last_y_used,y_date

1 个答案:

答案 0 :(得分:2)

我不会花时间理解或优化您的查询。只需将它们粘贴在子查询中并执行完全外连接:

SELECT * 
FROM (
   SELECT DISTINCT ON (usersq1.id) 
      usersq1.id AS user_id,
      usersq1.name,
      x_id       AS last_x_used, 
      started_at AS x_date
   FROM usersq1
   LEFT OUTER JOIN tripsq1
     ON usersq1.id = user_id
   ORDER BY usersq1.id 
) sub1
FULL OUTER JOIN (
   SELECT DISTINCT ON (usersq1.id) 
      usersq1.id AS user_id,
      usersq1.name,
      tripsq1.id AS trip_id, 
      y_id       AS last_y_used, 
      started_at AS y_date
   FROM usersq1
   LEFT OUTER JOIN tripsq1
     ON usersq1.id = user_id
   WHERE coupon_id IS NOT NULL
   ORDER BY usersq1.id, y_id DESC
) sub2 USING(user_id);