SQL。如何将现有表与刚刚生成的表(DB2)连接起来?

时间:2013-06-05 07:34:20

标签: sql join db2

我有下表:

enter image description here

我的任务是: 为每个事件选择项目,报告事件ID以及该事件的所有项目的总单位数。

我尝试了以下内容:

 SELECT S.ITEMNO,S.EVENTID, S.ROOMID, T.TOTAL                          
 FROM SELECTEDITEM S JOIN                                              
                    (SELECT EVENTID, SUM(UNIT_COUNT) AS TOTAL          
                    FROM SELECTEDITEM                                  
                    GROUP BY EVENTID) AS T                             
                    ON S.ITEMNO=T.ITEMNO;                              
---------+---------+---------+---------+---------+---------+---------+---------
DSNT408I SQLCODE = -206, ERROR:  T.ITEMNO IS NOT VALID IN THE CONTEXT WHERE IT 
         IS USED                                                               

为什么不起作用?我可以使用刚刚生成的表加入现有表吗?

2 个答案:

答案 0 :(得分:1)

SELECT S.ITEMNO,S.EVENTID, SUM(UNIT_COUNT) as total
FROM SELECTEDITEM S
GROUP BY S.ITEMNO,S.EVENTID

答案 1 :(得分:1)

你确定你不想要

SELECT S.ITEMNO,S.EVENTID, S.ROOMID, T.TOTAL                          
  FROM SELECTEDITEM S 
  JOIN (SELECT EVENTID, SUM(UNIT_COUNT) AS TOTAL          
          FROM SELECTEDITEM                                  
         GROUP BY EVENTID) AS T                             
    ON S.EVENTID=T.EVENTID;

问题是您的子选择没有t.ITEMNO列,因此ON子句无效。