我需要返回此查询的笛卡尔积和一个计算计数列平均值的新列。
select site_topics.description as topic,
site_subscriptions.site_user_id as user1,
count(*) as count1
from (
(site_topics_to_subscriptions
inner join site_subscriptions
on site_subscriptions.id = site_subscription_id)
inner join site_topics
on site_topics.id = site_topics_to_subscriptions.topic_id
)
group by user1,topic
order by user1, count1 desc;
当前结果:
-----------------------------------
topic |user1 |count1
-----------------------------------
Gaming |1 |3
Photography |1 |3
Art |1 |1
Gaming |2 |2
Photography |2 |1
Art |2 |1
所需的输出
-----------------------------------------------------
topic |user1 |count1 |user2 |count2 |Average
-----------------------------------------------------
Gaming |1 |3 |2 |2 |0.66
Photography |1 |3 |2 |1 |0.33
Art |1 |1 |2 |0 |0
Gaming |2 |2 |1 |3 |0.66
Photography |2 |1 |1 |3 |0.33
'平均'一个列,用该行的较大数量来计算较小的计数。同样的行也不会相互配对。即,不存在具有user1 = 1和user2 = 1
的行答案 0 :(得分:1)
一般结构应该是:
SELECT q1.user AS user1, q1.count AS count1, q2.user AS user2, q2.count AS count2, GREATEST(q1.count, q2.count)/LEAST(q1.count, q2.count) AS average
FROM (your query here) AS q1
JOIN (your query here) AS q2
ON q1.user < q2.user AND q1.topic = q2.topic
然后将获取原始表的查询替换为your query here
。创建一个执行原始查询的视图可能会有所帮助,因此您不必在交叉产品中重复整个过程。