减法SQLite

问题描述 投票:-1回答:1

我想在表上减去一列的两个值:

表名:统计

-|article|year|amount|
-|-------|----|------|
-|art1   |2018|289   |
-|art2   |2018|4512  |
-|art1   |2017|117   |
-|art2   |2017|1230  |
...

我使用了这个查询,但它不起作用:

-SELECT
-(CASE WHEN year = strftime('%Y', 'now') THEN s.amount END ) AS yearM,
-(CASE WHEN year = strftime('%Y', 'now')-1 THEN s.amount END ) AS yearM1,
-(yearM - yearM1) AS Delta
-FROM statistic AS s

yearM和yearM1列包含值,但Delta列为Empty

我找不到问题所在!

sqlite
1个回答
0
投票

你需要一个自我加入:

select s1.amount as yearM, s2.amount as yearM1, (s1.amount-s2.amount) as Delta 
from statistic s1, statistic s2 
where s1.year=strftime('%Y', 'now') 
and s2.year=strftime('%Y', 'now')-1 
and s1.article=s2.article;
© www.soinside.com 2019 - 2024. All rights reserved.