【问题标题】:Xcode, iphone, Sqlite, need a sign function for group by?Xcode, iphone, Sqlite, group by 需要签名功能吗?
【发布时间】:2011-01-26 11:26:46
【问题描述】:

我需要一个 sql sign 函数,用于我的 group by 查询来对正数和负数进行分组。

不幸的是 sqlite 不包括一个。

任何人都可以提出解决方法吗?或者如何添加一个与 xcode 中使用的 libsqlite3.dylib 框架一起使用?

我的查询很复杂

select fcid, sum(price), (select sum(price) from tmp b where ((b.due < a.due) 
or ((b.due = a.due) and (b.pid <= a.pid)))) as accumulated_price from tmp a 
where due >= '2011-01-25' and due < '2011-02-24' and price <> 0 group by fcid 
order by due, pid;

我想要做的是sign(price) 上的一个组,所以我得到两个结果和一个负值和一个正值。这些将代表总支出和总收入。

希望添加这些标签(但我不允许创建新标签 libsqlite3.dylib libsqlite3)

【问题讨论】:

    标签: iphone xcode sqlite


    【解决方案1】:

    不知道是不是你最好的选择,但你可以试试:

    select your_val > 0, sum(aggregated_value)
      from your_table
     group by your_val > 0;
    

    这样,您应该将0 用于零或负值,1 用于正值。

    更新:如果fcid 是您需要签名的字段,您可以尝试:

    select fcid > 0, sum(price), 
           (
             select sum(price) 
               from tmp b
              where ((b.due < a.due) or ((b.due = a.due) and (b.pid <= a.pid)))
           ) as accumulated_price 
      from tmp a 
     where due >= '2011-01-25' 
       and due < '2011-02-24' 
       and price <> 0 
     group by fcid > 0;
    

    请注意,您的 order by 子句是无用的,因为无论如何您都在对结果进行分组。

    【讨论】:

    • 如何在此查询中评估 your_val 为 NULL 的行?
    • 会有第三行:NULL |总和(聚合值)
    • 查看我的编辑,我的查询很复杂,不知道如何包含这些
    • @Jules:你需要签到的领域是什么?
    • 我会在价格上使用符号,按费用或收入进行分组。
    【解决方案2】:

    您应该只创建自己的符号函数。见Create or Redefine SQL Functions

    使用sqlite3_create_function注册一个函数:

    sqlite3_create_function( db, "sign", 1, SQLITE_ANY, NULL, signFunc,
                             NULL, NULL);
    

    然后在 C 中实现 signFunc。

    static void signFunc(sqlite3_context *c, int argCount, sqlite3_value **args) {
        if ( argCount != 1 ) {
            sqlite3_result_null( c );
            return;
        }
    
        switch ( sqlite3_value_type( args[0] ) ) {
            case SQLITE_INTEGER: {
                sqlite3_int64 asInt = sqlite3_value_int64( args[0] );
                sqlite3_int64 sign = asInt < 0 ? -1 : (asInt > 0 ? 1 : 0);
                sqlite3_result_int64( c, sign );
                break;
            }
            case SQLITE_FLOAT: {
                double asDouble = sqlite3_value_double( args[0] );
                sqlite3_int64 sign = asDouble < 0 ? -1 : (asDouble > 0 ? 1 : 0);
                sqlite3_result_double( c, sign );
                break;
            }
            case SQLITE_NULL:
            default: {
                sqlite3_result_null( c );
                break;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 2021-12-24
      相关资源
      最近更新 更多