我有这个查询,我需要在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
我需要做的是计算summeJ
和summeVJ
之间的差异,但我总是得到这个错误:“没有这样的列:summeJ”。有人可以帮我吗?
提前致谢
答案 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