关于union连接的几个表之间的计算

wvmv3b1j  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(251)

我有一个困难的查询,现在我需要将这个查询的结果从另一个表中分离出来。用过的工会。对吗?为什么我不工作?

SELECT * from (select IFnull(t.diapason,'total') as diapason, count(distinct 
user_id) / total_visitors*100 AS 'percent_of_users'
FROM 
(SELECT p.user_id, p.amount as total, CASE  
when amount<10 then '0-10' 
when amount>=10 then '10 +' END AS diapason
FROM 
    (SELECT payments.user_id, SUM(amount) AS amount 
    FROM payments INNER JOIN 
   (SELECT DISTINCT user_id, login_time FROM activity where login_time 
between '2018-04-12' and '2018-04-18') a 
ON payments.user_id = a.user_id and a.login_time = payments.payment_time 
GROUP BY payments.user_id) p
) t
  GROUP BY diapason WITH ROLLUP) as t1

UNION
SELECT COUNT(distinct user_id) as total_visitors FROM activity where 
login_time between '2018-04-12' and '2018-04-18'
ORDER BY percent_of_users desc;

我参加联合会是因为我需要吸引所有的访客。
谢谢!
结果呢

diapason    percent_of_visitors
0-10          ...%
10+           ...%

计算访问者的百分比(activity.user\u id的新值/activity.user\u id的旧值)。
但我不知道如何获得旧价值。你能给我一些提示吗?

gajydyqb

gajydyqb1#

从工作查询开始

SELECT ifnull(t.diapason,'total') as diapason,
   COUNT(DISTINCT user_id) AS user_count
FROM ...

你可以包括 total_visitors 使用子查询:

SELECT ifnull(t.diapason,'total') as diapason,
  COUNT(DISTINCT user_id) * 100 /
     (SELECT COUNT(distinct user_id) 
      FROM activity WHERE ...) as percent_of_users
FROM (...) t
GROUP BY diapason WITH ROLLUP
ORDER BY percent_of_users DESC

或者,您可以使用 join (更接近您想要的查询结构):

SELECT t1.diapason, 
  t1.user_count * 100 / tv.total_users as percent_of_users
FROM ( SELECT ifnull(t.diapason,'total') as diapason,
         COUNT(distinct user_id) AS user_count
       FROM ...
     ) as t1
CROSS JOIN (SELECT COUNT(distinct user_id) as total_visitors 
      FROM activity WHERE ...) as tv
ORDER BY percent_of_users DESC

我用了你的化名 t1 以及 t 标记查询的哪个部分属于何处。
在这两种情况下,总计数只会计算一次,但是mysql执行这两个查询的方式略有不同(虽然不会有太大的影响)。您可能需要包括一张支票,用于 0 (因此除以 0 ),尽管这不应该发生在这里。
备注:对于mysql 8+,如果使用cte,您可以稍微简化(和澄清)您的代码,因为您目前基本上重复子查询的代码 a 两次(一次在实际查询中,一次在总计数的计算中),如果它比一个简单的查询更复杂,那么它可能会变得烦人和混乱 where .

p5cysglq

p5cysglq2#

你想用这种模式做点什么。

SELECT a, b, c FROM tbl 
 UNION
 SELECT d FROM tbl

你不能那样做™. 联合中的两个结果集必须具有相同的列数,并且每一列在每个结果集中必须是相同的数据类型。

相关问题