【问题标题】:Joining Sqlite table on Subqueries在子查询上加入 Sqlite 表
【发布时间】:2020-06-01 11:43:22
【问题描述】:

我正在尝试加入基于分组列“年份”的 sqlite 表。我从一个返回数据库中所有年份的 select 子句开始,现在我想对同一个表进行子查询以获取各种统计信息并根据年份加入它。以下是我所拥有的。

select strftime('%Y', `date`, 'unixepoch') as `year` from transactions as t

left join (
    select sum(amount) as `expenses`, 
    strftime('%Y', `date`, 'unixepoch') as `year` from transactions
    where type = -1 and user_id = 1
    group by strftime('%Y', `date`, 'unixepoch')
) as e on e.year = t.year

left join (
    select sum(amount) as `income`, 
    strftime('%Y', `date`, 'unixepoch') as `year` from transactions
    where type = 1 and user_id = 1
    group by strftime('%Y', `date`, 'unixepoch')
) as i on i.year = t.year

group by strftime('%Y', `date`, 'unixepoch');

当我尝试运行该 sql 语句时,我得到“没有这样的列:t.year”。为什么我不能根据别名列加入?

【问题讨论】:

  • 请提供minimal reproducible examplecreate table ...insert ...几行的形式;也是与来自inserts 的样本数据匹配的所需输出。

标签: sqlite subquery


【解决方案1】:

transactions 别名为 t 不包含列 year(这是一个派生列)。
改为:

select strftime('%Y', t.`date`, 'unixepoch') as `year` from transactions as t

left join (
    select sum(amount) as `expenses`, 
    strftime('%Y', `date`, 'unixepoch') as `year` from transactions
    where type = -1 and user_id = 1
    group by strftime('%Y', `date`, 'unixepoch')
) as e on e.year = strftime('%Y', t.`date`, 'unixepoch')

left join (
    select sum(amount) as `income`, 
    strftime('%Y', `date`, 'unixepoch') as `year` from transactions
    where type = 1 and user_id = 1
    group by strftime('%Y', `date`, 'unixepoch')
) as i on i.year = strftime('%Y', t.`date`, 'unixepoch')

group by strftime('%Y', t.`date`, 'unixepoch');

我想您想要返回的连接表中的其他列虽然不在当前代码中。

我认为这是您想要实现的目标:

select 
  strftime('%Y', t.`date`, 'unixepoch') as `year` ,
  sum(case when type = -1 and user_id = 1 then amount end) as `expenses`,
  sum(case when type = 1 and user_id = 1 then amount end) as `income`
from transactions as t
group by strftime('%Y', t.`date`, 'unixepoch');

【讨论】:

  • 第二个实际上完全符合我的要求。我不知道我可以用 SQL 做到这一点。这不是我的主要语言。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 2011-06-23
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多