0

我想在查询中组合不同时期的不同总和

我使用以下查询来获得总和。

SELECT table1.BRS,
Sum(CASE WHEN table2.DATUM BETWEEN :van1 AND :tot1 THEN (DBBASIS-CRBASIS) ELSE (0) END)    
FROM table1 INNER JOIN table2 ON (table1.id= table2.id)    
WHERE table2.DATUM BETWEEN :van1 AND :tot1 
group by BRS

这可以正常工作。

如果我升级到第二个总和

SELECT table1.BRS,
Sum(CASE WHEN table2.DATUM BETWEEN :van1 AND :tot1 THEN (DBBASIS-CRBASIS) ELSE (0) END),
Sum(CASE WHEN table2.DATUM BETWEEN :van2 AND :tot2 THEN (DBBASIS-CRBASIS) ELSE (0) END)    
FROM table1 INNER JOIN table2 ON (table1.id= table2.id)    
WHERE table2.DATUM BETWEEN :van1 AND :tot1 or  table2.DATUM BETWEEN :van2 AND :tot2 
group by BRS

即使数据不同,我也会得到 2 个重复列的误报。该查询对第二个总和使用相同的日期。当我将第二个 Sum 更改为 Max 函数时,它使用第二个日期

如何结合这两个函数的结果。

PS:Interbase 不能使用

Select * from (Select Sum from...) Join (Select Sum from...)
4

1 回答 1

2

如果我正确理解了您的数据模型,那么:

SELECT  table1.BRS,
        Sum(t2a.DBBASIS-CRBASIS),
        Sum(t2b.DBBASIS-CRBASIS)
FROM    table1 LEFT JOIN table2 t2a ON (table1.id= t2a.id and t2a.DATUM BETWEEN :van1 AND :tot1)
        LEFT JOIN table2 t2b ON (table1.id = t2b.id and t2b.DATUM BETWEEN :van2 AND :tot2)
group by BRS

编辑:

SELECT  t1a.BRS,
        Sum(t1a.DBBASIS-CRBASIS),
        Sum(t1b.DBBASIS-CRBASIS)
FROM    table2 left join table1 t1a ON (table2.id= t1a.id and table2.DATUM BETWEEN :van1 AND :tot1)
        LEFT JOIN table1 t1b ON (table2.id = t1b.id and table2.DATUM BETWEEN :van2 AND :tot2)
group by t1a.BRS
于 2013-02-28T13:20:18.280 回答