sqlite查询对子查询的结果进行简单计算

时间:2013-09-02 12:29:31

标签: sql sqlite subquery

我有这个查询,我需要在sqlite(iOS)上做。

SELECT k.ZKUNDENNR, k.ZNAME1,
(SELECT SUM(vk.ZNETTO) FROM ZPBSROW r LEFT JOIN ZWARENGRUPPEVK vk ON vk.ZPBSROW=r.Z_PK WHERE r.ZKUNDE=k.Z_PK AND ZJAHR=2013 AND ZMONAT>=1 AND ZMONAT<=6) AS summeJ,
(SELECT SUM(vk.ZNETTO) FROM ZPBSROW r LEFT JOIN ZWARENGRUPPEVK vk ON vk.ZPBSROW=r.Z_PK WHERE r.ZKUNDE=k.Z_PK AND ZJAHR=2012 AND ZMONAT>=1 AND ZMONAT<=6) as summeVJ,
(SELECT SUM(vk.ZDB_BASIS) FROM ZPBSROW r LEFT JOIN ZWARENGRUPPEVK vk ON vk.ZPBSROW=r.Z_PK WHERE r.ZKUNDE=k.Z_PK AND ZJAHR=2012 AND ZMONAT>=1 AND ZMONAT<=6) as summeDBVJ,
(SELECT SUM(vk.ZDB_BASIS) FROM ZPBSROW r LEFT JOIN ZWARENGRUPPEVK vk ON vk.ZPBSROW=r.Z_PK WHERE r.ZKUNDE=k.Z_PK AND ZJAHR=2013 AND ZMONAT>=1 AND ZMONAT<=6) as summeDBJ, 
((summeJ-summeVJ)/summeVJ*100) AS variance FROM ZKUNDE k WHERE summeJ>0 ORDER BY summeJ DESC LIMIT 0,10

我需要做的是计算summeJsummeVJ之间的差异,但我总是得到这个错误:“没有这样的列:summeJ”。有人可以帮我吗? 提前致谢

1 个答案:

答案 0 :(得分:2)

您需要使用子查询,因为列别名无法在select的同一级别重复使用:

SELECT t.*, ((summeJ-summeVJ)/summeVJ*100) AS variance
FROM (SELECT k.ZKUNDENNR, k.ZNAME1,
             (SELECT SUM(vk.ZNETTO) FROM ZPBSROW r LEFT JOIN ZWARENGRUPPEVK vk ON vk.ZPBSROW=r.Z_PK WHERE r.ZKUNDE=k.Z_PK AND ZJAHR=2013 AND ZMONAT>=1 AND ZMONAT<=6) AS summeJ,
             (SELECT SUM(vk.ZNETTO) FROM ZPBSROW r LEFT JOIN ZWARENGRUPPEVK vk ON vk.ZPBSROW=r.Z_PK WHERE r.ZKUNDE=k.Z_PK AND ZJAHR=2012 AND ZMONAT>=1 AND ZMONAT<=6) as summeVJ,
             (SELECT SUM(vk.ZDB_BASIS) FROM ZPBSROW r LEFT JOIN ZWARENGRUPPEVK vk ON vk.ZPBSROW=r.Z_PK WHERE r.ZKUNDE=k.Z_PK AND ZJAHR=2012 AND ZMONAT>=1 AND ZMONAT<=6) as summeDBVJ,
             (SELECT SUM(vk.ZDB_BASIS) FROM ZPBSROW r LEFT JOIN ZWARENGRUPPEVK vk ON vk.ZPBSROW=r.Z_PK WHERE r.ZKUNDE=k.Z_PK AND ZJAHR=2013 AND ZMONAT>=1 AND ZMONAT<=6) as summeDBJ
      FROM ZKUNDE k
     ) t
WHERE summeJ>0
ORDER BY summeJ DESC
LIMIT 0,10