MySQL Query Simplication

时间:2017-11-18 17:52:39

标签: mysql aggregate-functions

我需要在sql查询的帮助下获得每个配额的总和。现在我使用两个查询来获得结果。但我希望通过运行单个查询来获得结果,以最大限度地减少时间和代码。这是我的第一个查询。

SELECT DISTINCT master.account_code, master.account_name FROM 0_chart_master AS master WHERE master.account_type IN (60,61,233)

从上面的查询中,它将显示帐户代码的结果,如下所示。

1700  Payroll Expenses
1710  Rent
1720  Travel Expenses
4000  Miscellaneous

从我用过的每个帐户代码中查询以下查询。

SELECT SUM(amount) FROM 0_gl_trans WHERE account='1700' AND tran_date >= '2017-10-31' AND tran_date <= '2017-11-30'
SELECT SUM(amount) FROM 0_gl_trans WHERE account='1710' AND tran_date >= '2017-10-31' AND tran_date <= '2017-11-30'
SELECT SUM(amount) FROM 0_gl_trans WHERE account='1720' AND tran_date >= '2017-10-31' AND tran_date <= '2017-11-30'
SELECT SUM(amount) FROM 0_gl_trans WHERE account='4000' AND tran_date >= '2017-10-31' AND tran_date <= '2017-11-30'

我需要一个针对这种困难情况的简化解决方案。

4 个答案:

答案 0 :(得分:4)

您可以在第一个结果的附加列中获得总计:

SELECT    master.account_code, master.account_name, COALESCE(SUM(trans.amount), 0) AS total 
FROM      0_chart_master AS master
LEFT JOIN 0_gl_trans AS trans 
       ON trans.account = master.account_code
      AND trans.tran_date BETWEEN '2017-10-31' AND '2017-11-30'
WHERE     master.account_type IN (60,61,233)
GROUP BY  master.account_code, master.account_name

答案 1 :(得分:1)

您只需过滤帐户并汇总:

function custom_comparison(a, b, c, d) {
return a > c || a === c && b > d;
}

答案 2 :(得分:1)

你可以用这种方式选择

  select master.account_code, master.account_name,
    sum( case when account='1700' then amount else 0 end ) tot_1700_payroll_Expenses,
        sum( case when account='1710' then amount else 0 end ) tot_1710_Rent,
        sum( case when account='1720' then amount else 0 end ) tot_1720_Travel_Expenses,
        sum( case when account='4000' then amount else 0 end ) tot_4000_Miscellaneous
  FROM 0_gl_trans WHERE  tran_date >= '2017-10-31' AND tran_date <= '2017-11-30'
  INNER JOIN _chart_master AS master ON master.account_code = 0_gl_trans.account 
          and  master.account_type IN (60,61,233)
  group by master.account_code, master.account_name

答案 3 :(得分:1)

您可以使用第一个查询作为子查询来获取相关Between...AND,并且可以使用SELECT COALESCE(SUM(amount), 0), account FROM 0_gl_trans WHERE account in (SELECT DISTINCT master.account_code FROM 0_chart_master AS master WHERE master.account_type IN (60,61,233) ) AND tran_date between '2017-10-31' AND '2017-11-30' group by account; 作为日期条件。 请尝试以下查询:

MedianHeap

希望它有所帮助!