SQLITE选择值总和相同的ID

时间:2017-05-14 10:43:29

标签: android sqlite

我有一个名为Transactions的表,其中包含以下模式:

ID  |   P_Name   |  O_ID |   P_ID  |   P_Qty   |
===============================================
1   | PRODUCT A  |   1   |   140   |   100     |
2   | PRODUCT A  |   1   |   140   |   15      |
3   | PRODUCT B  |   1   |   130   |   10      |
4   | PRODUCT C  |   1   |   120   |   2       |

我想总结所有共享P_Name的P_Qty,这样我最终可以得到:

P_Name    | P_ID  |  P_Qty    |
===============================
PRODUCT A | 140   |   115     |
PRODUCT B | 130   |   10      |
PRODUCT C | 120   |   2       |

正如您所看到的,P_Qty是P_ID相同的总和,我使用的是ContentResolver,如下所示,但是如图所示失败:

    String selection = null;

    String[] selectionArgs = null;

    String orderBy = TRANSACTION_PRODUCT_NAME  + " ASC";

    Cursor cursor = getActivity().getContentResolver().query(
            SalesManContract.TRANSACTION_CONTENT_URI,
            new String[] {TRANSACTION_PRODUCT_NAME," SUM(P_Qty) AS 
            P_Qty"},
            selection,
            selectionArgs,
            orderBy);

结果是:

 P_Name    | P_ID  |  P_Qty    |
===============================
PRODUCT A | 140   |   127     |

如何使用ContentResolver实现我想要的结果

1 个答案:

答案 0 :(得分:0)

问题是您必须在查询中使用分组依据。我认为这应该对你有帮助:

Android: Distinct and GroupBy in ContentResolver