【问题标题】:How do you perform a Group By function on a subquery?如何对子查询执行 Group By 功能?
【发布时间】:2016-01-30 20:31:47
【问题描述】:

我正在使用一个包含联系人、消息、收件人和对话的数据库。

我使用 user_ID 作为标准在联系人和收件人之间执行了完全外部联接。这将给出一个包含这些值的表格; USER_ID、FNAME、LNAME、CELL、CITY、COUNTRY、MSGID、USER_ID、TIME_READ。 user_ID 有重复的值,因为两个表都有这个值。我的子查询在自己完成时会给出正确的结果:

SELECT *
FROM Contacts
FULL JOIN Recipients
ON Contacts.user_ID=Recipients.user_ID;

完成此操作后,我想执行一个 Group By,他们计算每个 user_ID 的每个 msgID,以给出 user_ID 的最终结果和每个用户收到的消息数。

我似乎无法让语法正确,因为我不断收到错误。

SQL> SELECT user_ID, count(msgID)
FROM (  SELECT *
    FROM Contacts
    FULL JOIN Recipients
    ON Contacts.user_ID=Recipients.user_ID)
Group by Contacts.user_ID; 

Group by Contacts.user_ID
         *
ERROR at line 6:
ORA-00904: "CONTACTS"."USER_ID": invalid identifier

我尝试过“Contacts.user_ID”和简单的“user_ID”,但它不喜欢任何一种变体。

谢谢。

【问题讨论】:

    标签: sql oracle select join group-by


    【解决方案1】:

    我猜你想要这个:

    SELECT COALESCE(c.user_ID, r.user_ID), COUNT(*)
    FROM Contacts c FULL JOIN
         Recipients r
         ON c.user_ID = r.user_ID
    GROUP BY COALESCE(c.user_ID, r.user_ID);
    

    子查询不是必需的。

    【讨论】:

    • 谢谢!这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多