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

时间:2015-01-23 19:28:43

标签: android sqlite android-sqlite

我有以下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和timestamp排序。这样做他们被分组但不是所有对产品 - 超市都有相同的时间戳,所以有可能获得所有配对产品 - 具有相同数量的时间戳的超市?如果货品超市没有时间戳,则在返回的结果中将其价格设置为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_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中执行?

1 个答案:

答案 0 :(得分:1)

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

然后用价格outer join做一个:{/ 3>

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)

对于缺失的价格,这将返回NULL。 如果你真的想要零,请改用IFNULL(price.price, 0.0)