附图显示了结果集,我将在下面留下我的代码 - 为什么我无法计算viewTotal
每个单元格中整列的总和?我希望viewTotal
列下的每个单元格都可以读取4
。
我想这是某种分组问题,尽管我在网上找不到关于哪些列需要分组的具体信息。保留所有三行很重要 - 我不想只返回一行。也许这个标准使我想做的事情变得更加困难?
谢谢你,埃文
Select topic_id, topic_subject, SUM(topicViews) as viewTotal, replyCount From
(
Select
T.topic_id, T.topic_subject, Count(distinct Tvt.id) as topicViews, Count(Distinct R.reply_id) as replyCount, R.reply_id, R.reply_topic
From topic T
LEFT JOIN topic_view_tracker Tvt ON
T.topic_id = Tvt.topic_id
LEFT Join reply R ON
T.topic_id = R.reply_topic
Where
T.topic_by = 10
Group By T.topic_id) B
Group By topic_id
Order by replyCount DESC
样本记录:
主题表
╔══════════╦════════════════════════════╦══════════╗
║ TOPIC_ID ║ TOPIC_SUBJECT ║ TOPIC_BY ║
╠══════════╬════════════════════════════╬══════════╣
║ 25 ║ School police in the night ║ 10 ║
║ 29 ║ The first topic, enjoy it ║ 10 ║
║ 30 ║ This is a normal title... ║ 10 ║
╚══════════╩════════════════════════════╩══════════╝
TOPIC_VIEW_TRACKER表
╔════╦════════════╦══════════╗
║ ID ║ USER_IP ║ TOPIC_ID ║
╠════╬════════════╬══════════╣
║ 1 ║ xx.xx.xx.x ║ 25 ║
║ 2 ║ xx.xx.xx.x ║ 25 ║
║ 3 ║ xx.xxx.xxx ║ 29 ║
║ 4 ║ xxx.xx.xx ║ 30 ║
╚════╩════════════╩══════════╝
回复表
╔══════════╦═════════════╗
║ REPLY_ID ║ REPLY_TOPIC ║
╠══════════╬═════════════╣
║ 1 ║ 25 ║
║ 2 ║ 29 ║
╚══════════╩═════════════╝
预期输出(示例):
topic_id 主题 主题视图 总回复数 29 第一个话题,好好享受 4 5 夜间 25 名校警 4 4 30 这是一个主题的正常标题... 4 0