SQLite - 返回列总数w /所有行

时间:2012-09-08 07:44:37

标签: sql sqlite

我有以下SQLite表:

transaction_amount     transaction_date
50                     09/06/2012
50                     09/06/2012
75                     09/07/2012

我希望获得该列的总金额,transaction_amount。如果我像这样写我的SQL查询:

SELECT transaction_amount,transaction_date, SUM(transaction_amount) AS 
Total FROM prepaid_tbl WHERE playerID = 17 ORDER BY id DESC

我得到以下结果:

 transaction_amount     transaction_date  Total
 75                     09/07/2012        175

我需要返回所有三行以及总数。所以,如果我像这样编写SQL语句:

SELECT transaction_amount,transaction_date,(SELECT SUM(transaction_amount) 
FROM prepaid_tbl WHERE playerID = 17)Total FROM prepaid_tbl WHERE 
playerID = 17 ORDER BY id DESC

我现在得到我要找的结果:

transaction_amount     transaction_date    Total
50                     09/06/2012          175
50                     09/06/2012          175
75                     09/07/2012          175

所以,我的简单问题是获得理想结果的最佳方法/实践。我无论如何都不是SQL专家,所以我仍然不确定为什么第一种方法没有返回我想要的结果。任何见解当然都值得赞赏。

提前谢谢。

1 个答案:

答案 0 :(得分:2)

您可以cartesian join解决问题

SELECT  a.transaction_amount,
        a.transaction_date,
        b.Total
FROM prepaid_tbl  a,
        (
            SELECT  SUM(transaction_amount) AS  Total 
            FROM prepaid_tbl 
            WHERE playerID = 17 
        ) b
WHERE a.playerID = 17 

SQLFiddle Demo