我想在查询中将不同时期的不同总和组合起来
我使用以下查询来获得总和。
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函数时,它使用Second second
如何组合这两个功能的结果。
PS:Interbase无法使用
Select * from (Select Sum from...) Join (Select Sum from...)
答案 0 :(得分: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