Android 中具有相同行数的 SQLite 返回组

SQLite returning groups with same number of rows in Android

我有以下 SQLite 查询:

        select  
                product._id
                supermarket._id
                datetime(price.timestamp,'localtime') as LOCAL_TIMESTAMP,
                price.price
        from price inner join product on price.productid = product._id
                   inner join supermarket on price.supermarketid = supermarket._id

        order by price.productid, price.supermarketid, price.timestamp

行按 productid、supermarketid 和时间戳排序。这样做是对它们进行了分组,但并非所有产品超市对都具有相同的时间戳,因此是否有可能获得具有相同数量时间戳的所有产品超市对?如果 pair product-supermarket 没有时间戳,则在 returned 结果中将其价格设置为 0。

例如,上面的查询可能 return:

Product_A Supermarket_A "2014-03-10 00:00:00"   2.3
Product_A SUpermarket_A "2014-04-10 00:00:00"  15.0
Product_A SUpermarket_A "2014-04-20 00:00:00"  10.5

Product_B Supermarket_A "2014-01-01 00:00:00"  23.3
Product_B SUpermarket_A "2014-05-21 00:00:00"   1.0

我想获得:

Product_A Supermarket_A "2014-01-01 00:00:00"   0.0
Product_A Supermarket_A "2014-03-10 00:00:00"   2.3
Product_A SUpermarket_A "2014-04-10 00:00:00"  15.0
Product_A SUpermarket_A "2014-04-20 00:00:00"  10.5
Product_A SUpermarket_A "2014-05-21 00:00:00"   0.0

Product_B Supermarket_A "2014-01-01 00:00:00"  23.3
Product_B Supermarket_A "2014-03-10 00:00:00"   0.0
Product_B Supermarket_A "2014-04-10 00:00:00"   0.0
Product_B Supermarket_A "2014-04-20 00:00:00"   0.0
Product_B SUpermarket_A "2014-05-21 00:00:00"   1.0

在每个产品-超市对中出现所有时间戳(如联合)。如果产品-超市对没有时间戳,则创建它并将其价格设置为 0.0。

是否可以在 SQL 中完成?

要获得所有可能的 时间戳组合,使用时间戳进行连接,但不使用连接条件。 (这里需要 DISTINCT 以避免重复。)

然后 outer join 价格:

SELECT productid,
       supermarketid,
       datetime(timestamp, 'localtime') AS local_timestamp,
       price.price
FROM (SELECT DISTINCT product._id     AS productid,
                      supermarket._id AS supermarketid
      FROM       product 
      INNER JOIN price       ON product._id         = price.productid
      INNER JOIN supermarket ON price.supermarketid = supermarket._id)
CROSS JOIN (SELECT DISTINCT timestamp
            FROM price)
LEFT JOIN price USING (productid, supermarketid, timestamp)

此 returns NULL 表示缺少价格。 如果您真的想要一个零,请改用 IFNULL(price.price, 0.0)