`使用SUM和GROUP BY将mySQL查询转换为SQLite

时间:2014-08-30 14:20:45

标签: mysql sqlite

我正在开发一个移动应用程序,该应用程序当前正在使用ajax调用远程运行mySQL查询并将数据作为数组返回。我想使用SQLite 3和iPad在本地运行查询。下面是mySQL查询。我无法让查询在SQLite中工作

这是我的mySQL查询

SELECT 
 expense_date.expenseDate,
 expenses.cost,
 SUM(expenses.cost) as total,
 expenses.name,
 category.category
 FROM expenses
 INNER JOIN category ON expenses.catID = category.catID
 INNER JOIN expense_date ON expenses.dateID = expense_date.dateID
WHERE expense_date.expenseDate BETWEEN '#from#' AND '#tu#'
  AND expenses.catID != '1F27C7A1-3E16-5087-A313-A47D286A77A5'
  AND expenses.catID != 'DF64C183-5056-A816-1ACA94F902242B61'
  AND expenses.userID = '#userID#'
  AND expenses.accountID = '#accountID#'
Group By expense_date.expenseDate

更新的MySQL声明。此语句适用于mySQL,但不适用于SQLite 3。

SELECT 
     expense_date.expenseDate,
     SUM(expenses.cost) as total
     FROM expenses
     INNER JOIN expense_date ON expenses.dateID = expense_date.dateID 
    WHERE expense_date.expenseDate 
        BETWEEN '2014-08-01' AND '2014-08-31'  
        AND expenses.catID != '1F27C7A1-3E16-5087-A313-A47D286A77A5' 
        AND expenses.catID != 'DF64C183-5056-A816-1ACA94F902242B61' 
        AND expenses.userID = 'C4C73329-5056-A816-1AB4B9FAE08FDB77' 
        AND expenses.accountID = '46298719-C78A-4CCE-8ADD-A3FD948DF93E' 
        Group By expense_date.expenseDate

这是查询的结果。 2014-08-21有两个值为该日期:2000.00和372.00但它们被加在一起并作为2014-08-21的单一值返回。

2014-08-01  32.00
2014-08-16  15.00
2014-08-19  513.55
2014-08-21  2372.00
2014-08-22  525.00
2014-08-25  34.55
2014-08-27  52.78
2014-08-31  30.00

我需要将MySQL查询代码转换为SQLite。我做了谷歌搜索,发现了一些关于使用CASE的信息,但我不知道如何构造sql语句。感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您的SQL查询实际上在MySQL中没有意义,因为几个选定的值是不确定的。您可以尝试这样的事情:

SELECT ed.expenseDate, SUM(e.cost) as total,
       group_concat(e.name) as names,
       group_concat(c.category) as categories
FROM expenses e INNER JOIN
     category c
     ON e.catID = e.catID INNER JOIN
     expense_date ed
     ON e.dateID = ed.dateID
WHERE ed.expenseDate BETWEEN '#from#' AND '#tu#'  AND
      e.catID <> '1F27C7A1-3E16-5087-A313-A47D286A77A5' AND
      e.catID <> 'DF64C183-5056-A816-1ACA94F902242B61' AND
      e.userID = '#userID#' AND
      e.accountID = '#accountID#'
Group By ed.expenseDate;

答案 1 :(得分:0)

这是解决我问题的SQLite sql语句。

SELECT expense_date.expenseDate, 
SUM(expenses.cost) AS total 
FROM expenses INNER JOIN expense_date ON expenses.dateID = expense_date.dateID 
WHERE expense_date.expenseDate BETWEEN '"+from+"' AND '"+tu+"' 
AND expenses.catID <> '1F27C7A1-3E16-5087-A313-A47D286A77A5' 
AND expenses.catID <> 'DF64C183-5056-A816-1ACA94F902242B61' Group By expense_date.expenseDate

感谢大家的帮助。