在非聚合查询中嵌入聚合查询

时间:2013-11-21 13:38:55

标签: sql oracle select count subquery

我正在尝试创建一个数据库视图,该视图具有列值的聚合查询结果(有关所使用的聚合查询,请参阅this post),例如:

之类的东西
MESSAGEVIEW
----------------------------------------------
MESSAGEID    SENDER       PARTCOUNT        
----------------------------------------------
1            Tim          2
2            Bridgekeeper 0

我已经尝试过这段代码来选择视图数据:

SELECT m.MESSAGEID, m.SENDER,
    (SELECT COUNT(mp.MESSAGEID)
         FROM MESSAGE m LEFT JOIN MESSAGEPART mp
         ON mp.MESSAGEID = m.MESSAGEID GROUP BY m.MESSAGEID) AS PARTCOUNT
    FROM MESSAGE m;

返回ORA-01427: single-row subquery returns more than one row

我也试过

SELECT m.MESSAGEID, m.SENDER, COUNT(mp.MESSAGEID) AS PARTCOUNT
FROM MESSAGE m
LEFT JOIN MESSAGEPART mp ON mp.MESSAGEID = m.MESSAGEID 
GROUP BY m.MESSAGEID;

返回ORA-00979: not a GROUP BY expression

如何获得正确显示此信息的视图?

3 个答案:

答案 0 :(得分:1)

这应该这样做。

SELECT m.MESSAGEID, m.SENDER,
    (SELECT COUNT(mp.MESSAGEID)
         FROM MESSAGEPART mp
         WHERE mp.MESSAGEID = m.MESSAGEID) AS PARTCOUNT
    FROM MESSAGE m;

答案 1 :(得分:1)

您可以使用子查询(请参阅@Jva答案)或使用以下JOIN来执行此操作:

SELECT m.MESSAGEID, m.SENDER,
       mp.PartCount AS PARTCOUNT

       FROM MESSAGE m
           LEFT JOIN 
             (SELECT MESSAGEID,COUNT(*) as PartCount 
                     FROM MESSAGEPART GROUP BY MESSAGEID) as mp 
             ON m.MESSAGEID=mp.MESSAGEID

答案 2 :(得分:1)

如果在窗口函数格式中使用count(),则可以将其放入没有子查询的单个查询中:

SELECT m.MESSAGEID, m.SENDER, COUNT(mp.MESSAGEID) OVER (PARTITION BY m.MESSAGEID) AS PARTCOUNT
FROM MESSAGE m
LEFT JOIN MESSAGEPART mp ON mp.MESSAGEID = m.MESSAGEID;