douyakao5308 2018-02-09 21:59
浏览 44
已采纳

尝试将两个分组查询合并为一个

I'm trying to get a list of all the clicks and sales associated with an account, with both tables having the account ID as an index. Right now I have:

SELECT ACCOUNT, SUM(REVENUE) AS R, COUNT(*) AS SALES
FROM CONVERSIONS
WHERE ACCOUNT = ? AND TIME BETWEEN ? AND ? GROUP BY ACCOUNT

AND

SELECT ACCOUNT, COUNT(DISTINCT BIN_IP) AS CLICKS
FROM CLICKS
WHERE ACCOUNT = ? AND TIME BETWEEN ? AND ? GROUP BY ACCOUNT

That gives me both lists, but then I have to do a ton of array manipulation to get them to uniquely line up. Trying to see if there's a way to join both queries, but thus far everything I've tried has failed.

Edit: For clarity, my issue with every join I've tried is I lose the case that theres sales and no clicks, or clicks and no sales. Joining them and checking that the table.ACCOUNT = table2.ACCOUNT only works if there's both clicks and sales present. This is essentially the part of the puzzle I'm struggling with.

  • 写回答

2条回答 默认 最新

  • dtgv52982 2018-02-09 22:42
    关注

    If you are happy with the queries you have, you can use:

    SELECT conv.ACCOUNT, conv.R, conv.SALES, clicks.CLICKS
    FROM
    (SELECT ACCOUNT, SUM(REVENUE) AS R, COUNT(*) AS SALES
     FROM CONVERSIONS
     WHERE ACCOUNT = ? AND TIME BETWEEN ? AND ? GROUP BY ACCOUNT) conv
    LEFT JOIN
    (SELECT ACCOUNT, COUNT(DISTINCT BIN_IP) AS CLICKS
     FROM CLICKS
     WHERE ACCOUNT = ? AND TIME BETWEEN ? AND ? GROUP BY ACCOUNT) clicks
    ON conv.ACCOUNT = clicks.ACCOUNT
    UNION
    SELECT clicks2.ACCOUNT, conv2.R, conv2.SALES, clicks2.CLICKS
    FROM
    (SELECT ACCOUNT, COUNT(DISTINCT BIN_IP) AS CLICKS
     FROM CLICKS
     WHERE ACCOUNT = ? AND TIME BETWEEN ? AND ? GROUP BY ACCOUNT) clicks2
    LEFT JOIN
    (SELECT ACCOUNT, SUM(REVENUE) AS R, COUNT(*) AS SALES
     FROM CONVERSIONS
     WHERE ACCOUNT = ? AND TIME BETWEEN ? AND ? GROUP BY ACCOUNT) conv2
    ON clicks2.ACCOUNT = conv2.ACCOUNT
    

    This is messy because mySQL does not have a FULL JOIN. So instead you have to use two left join and UNION. Note that the first set of joins, conv and clicks, will include cases where there are only conversion records and where there are records in both tables. The second set of joins, conv2 and clicks2, will return cases where there are only clicks.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算