1

我从几个表中选择:

 SELECT  SUM(S2.F64)   as sumAll
 FROM someTABLE1 S1
 LEFT OUTER JOIN someTABLE2 S2 ON S2.F32 = S1.F32 
 WHERE S2.F01 = '1006'
 and S2.F68='ORDER' AND S1.F67='ITEM'

现在我想从另一个选择中获取 S1.F01 的值:像这样

SELECT S3.F01
FROM someTABLE3 S3
WHERE "something..."

所以我想要这样的东西:

SELECT  SUM(S1.F64) as sumAll, S3.F01  
FROM someTABLE3 S3
LEFT OUTER JOIN someTABLE1 S1 ON S1.F01 = S3.F01
LEFT OUTER JOIN someTABLE2 AS S2 ON S1.F32 = S2.F32 
WHERE S1.F01 = S3_F01
and S2.F1068='ORDER' AND S1.F1067='ITEM'

但是,我想获取 S3 中的所有项目,并在 sumAll 中填充条件匹配的列。

所以我想要这样的东西(伪代码):

SELECT * from S3
FOR EVERY (S3.F01)
{
    SELECT * FROM S1
    if(S1.F1067='ITEM')
        RETURN S3 AND SUM(S1.F64)
    ELSE 
        RETURN S3
}

反正有这样做吗?

4

2 回答 2

1

你只是在寻找GROUP BY吗?

SELECT  SUM(S1.F64) as sumAll, S3.F01  
FROM someTABLE3 S3
    LEFT OUTER JOIN someTABLE1 S1 ON S1.F01 = S3.F01
    LEFT OUTER JOIN someTABLE2 AS S2 ON S1.F32 = S2.F32 
WHERE S2.F1068='ORDER' AND S1.F1067='ITEM'
GROUP BY S3.F01

编辑 - 将 where 条件移动到连接...

SELECT  SUM(S1.F64) as sumAll, S3.F01  
FROM someTABLE3 S3
    LEFT OUTER JOIN someTABLE1 S1 ON S1.F01 = S3.F01 AND S1.F1067='ITEM'
    LEFT OUTER JOIN someTABLE2 AS S2 ON S1.F32 = S2.F32 AND S2.F1068='ORDER'
GROUP BY S3.F01

SQL小提琴

于 2013-11-15T00:05:10.260 回答
0

不完全确定我完全理解你,但这里有一个方法来做到这一点:

SELECT  S3.*, SQ.sumValue
FROM someTABLE3 S3
LEFT JOIN( SELECT F01,SUM(F64)
          FROM someTable1
          WHERE F1067='ITEM'
          GROUP BY F01) SQ ON SQ.F01 = S3.F01
LEFT JOIN someTable1 AS S1 ON S1.F01 = S3.F01
LEFT JOIN someTABLE2 AS S2 ON S1.F32 = S2.F32  AND S2.F1068='ORDER'

您在获得SUM(F64) GROUP BY F01on的地方进行内部查询table1。这样,当你执行LEFT JOINfrom table3to that 时,你会得到所有的table3和 K 或SUM你想要的。

然后对于LEFT JOINwith table2,我先做一个LEFT JOINwith ,table1因为我不知道你是否可以table2table3.

这有点令人困惑,但我希望你能理解这种方法

于 2013-11-15T00:38:20.373 回答