在一段时间内选择sql记录

时间:2014-07-21 11:58:18

标签: mysql sql

我的表格如下图所示,所有负面ContributionAmount都是退款,正值是会员付款。 我想只选择一年中所有退款和所有捐款,所以我在下面创建了查询。但我对查询感到不舒服,它感觉不专业,我觉得有更好的方法来做这个,尤其是性能。另外,当我想获取特定成员的信息时,我必须在每个子查询中添加一个额外的WHERE语句。

所以我的问题是我如何构建一个更好的查询,以便我不必重复这样的代码,以便查询更好,我真的很感激所有的答案。感谢..

ContributionID MemberID ContributionAmount ContributionDate
             1        2           5000.000 2014-01-31
             2        2          10000.000 2013-12-31
             3        2          15000.000 2014-07-31
             4        3         115000.000 2014-07-22
             5        3          40000.000 2014-07-09
             6        2         115000.000 2014-07-14
             7        2           5000.000 2014-01-31
             8        2           5000.000 2015-01-31
             9        2           5000.000 2014-12-31
            10        2           5000.000 2014-02-28 
            11        3  3000000000000.000 2014-07-31
            12        2         115000.000 2014-07-21
            13        2           5000.000 2014-07-31
            14        3          -15000.000 2013-07-31

SELECT
(
    SELECT 
        SUM(ca.`ContributionAmount`) 
    FROM contributions_account ca
    WHERE ca.`ContributionAmount` < 0
    AND YEAR(ca.`ContributionDate`) ='2013'
)AS TotatlRefund,
(
    SELECT 
        SUM(ca.`ContributionAmount`) 
    FROM contributions_account ca
    WHERE ca.`ContributionAmount` > 0
    AND YEAR(ca.`ContributionDate`) ='2013'
)AS TotalContribution,
(
    SELECT 
        SUM(ca.`ContributionAmount`) 
    FROM contributions_account ca
    WHERE YEAR(ca.`ContributionDate`) ='2013'
)AS ContributionBalance

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
 SUM(CASE WHEN ContributionAmount >= 0 THEN 0 ELSE ContributionAmount END) TotalRefund,
 SUM(CASE WHEN ContributionAmount <= 0 THEN 0 ELSE ContributionAmount END) TotalContribution,
 SUM(ContributionAmount) ContributionBalance
  FROM contributions_account
 WHERE YEAR(ContributionDate) ='2013'

要提高性能并在ContributionDate上使用索引,请将WHERE更改为:

WHERE ContributionDate BETWEEN '2013' AND '2014'

由于MySQLDate视为字符串,因此此比较有效。我相信使用列上的YEAR函数会阻止查询使用索引。

答案 1 :(得分:1)

试试这个:

SELECT
        SUM(CASE WHEN ca.`ContributionAmount` < 0 THEN ca.`ContributionAmount` ELSE 0 END) AS TotatlRefund,
        SUM(CASE WHEN ca.`ContributionAmount` > 0 THEN ca.`ContributionAmount` ELSE 0 END) AS TotalContribution,
        SUM(ca.`ContributionAmount`) AS ContributionBalance
FROM    contributions_account ca
WHERE   YEAR(ca.`ContributionDate`) = '2013'