首页 > 解决方案 > SQLite 如何使用生成的列在同一个查询中进行额外的计算

问题描述

我习惯了 SAS 中的 sql 语法,它允许使用基于聚合函数的其他生成列创建额外的计算。例如:

select date(created_at) as date,
       count(distinct case when platform = 'Android' then user_id end) as 
       Android,
       count(distinct case when platform = 'iOS' then user_id end) as iOS,
       calculated Android + calculated iOS as Total
from dataset
group by 1;

我的问题是在上面创建的最后一列“总计”上。SAS 有一个称为“计算”的内置函数,它可以识别已经生成的列并允许使用该列进行其他计算。

SQLite 中是否存在类似的东西,或者子查询是唯一的其他选择?

标签: sqlsqlite

解决方案


您需要在标准 SQL 中使用子查询或 CTE:

select d.*, (Android + iOS) as Total
from (select date(created_at) as date,
             count(distinct case when platform = 'Android' then user_id end) as Android,
             count(distinct case when platform = 'iOS' then user_id end) as iOS,
      from dataset
      group by date(created_at)
     ) d;

calculated关键字proc sql是. 但是,它在其他数据库中不可用。


推荐阅读